Reputation: 9415
I have a file (show.json.erb) in which I'm formatting a model as json. In my app, Projects have many Steps and many Images, and Steps have many Images.
I'd like to be able to include only a default image for a project, which I'm trying to do using "conditions." However, it seems to be ignoring the conditions and posting all the images associated with a project. How do I include only the right images?
"projects":
<%= JSON.pretty_generate(@projects.order("updated_at DESC").as_json(only: [:title, :id,
:built, :updated_at], include: {images: {only: [:image_path],
:conditions=>['Step.find(image.step_id).name.eql? "Project Overview"', true] }
})).html_safe %>
Upvotes: 0
Views: 527
Reputation: 9415
I solved this problem by creating a method called image_path in my Projects model:
(I needed the method to return three types of images)
def image_path
images = Hash.new
if first_step.images.present?
images["url"] = first_step.first_image.image_path_url
images["preview"] = first_step.first_image.image_path_url(:preview)
images["thumbnail"] = first_step.first_image.image_path_url(:thumb)
end
return images
end
Then I edited my JSON to look like this:
"projects":
<%= JSON.pretty_generate(@projects.order("updated_at DESC").as_json(only: [:title, :id, :built], :methods=> [:image_path, :updated_at_formatted])).html_safe %>
This gets rendered like this on my website:
"projects":
[
{
"built": true,
"id": 115,
"title": "Video Test",
"image_path": {
"url": "https://s3.amazonaws.com/...",
"preview": "https://s3.amazonaws.com/...",
"thumbnail": "https://s3.amazonaws.com/..."
},
"updated_at_formatted": "07/08/2013 10:31:19"
},
...]
Hope this helps someone else!
Upvotes: 2