Jbuilder代码:
json.array!(@venues) do |venue|
json.extract! venue, :id, :name, :longitude, :latitude, :price_range, :venue_category_id, :venue_images, :address, :short_description, :max_capacity
end在我的模型中,每一个‘场地’has_many‘场馆_图像’。上面的JSON在主场馆数组中为venue_images提供了一个对象数组,就像预期的那样。
venue_image对象如下所示:
#<Item:0x007fc97559b960> {
:id => 1,
:image_content_type => "image/jpeg",
:image_file_name => "chanel.jpg",
:image_file_size => 28880,
:image_updated_at => 2012-04-09 21:00:08 UTC
}我需要以某种方式遍历jbuilder代码中的场馆图像,以便在它们上调用Paperclip/S3帮助程序(即.image.url(:medium)),因为它们在JS视图中是不可用的。我需要把这些urls放到@ properties数组中,而不是让回形针对象的所有其他属性,这样我就可以在JS中迭代它们,并在我的视图中显示它们。
做这件事最好的方法是什么?我尝试了几个不同的块,查看了jbuilder和几篇文章,但是没有任何东西可以工作。
谢谢
发布于 2014-05-20 06:26:47
如果我对你的理解是正确的,你是这么想的吗:
json.array!(@venues) do |venue|
json.extract! venue, :id, :name, :longitude, :latitude, :price_range, :venue_category_id, :address, :short_description, :max_capacity
json.venue_images venue.venue_images do |vi|
json.url vi.image.url(:medium))
json.id vi.id
json.image_content_type "image/jpeg"
json.image_file_name "chanel.jpg"
json.image_file_size 28880
json.image_updated_at "2012-04-09 21:00:08 UTC"
end
end这将为您提供如下JSON哈希:
"venue": {
"id": 1,
"name": "Foo",
"longitude": "180 degrees",
"latitude": "90 degrees",
"price_range": "100-200",
"venue_category_id": 2,
"address": "500 Poop Lane",
"short_description": "Blah blah, foo foo",
"max_capacity": 500,
"venue_images": [
{
"url": "http://poop.com",
"id": 5,
"image_content_type": "image/jpeg",
"image_file_name": "chanel.jpg",
"image_file_size": 28880,
"image_updated_at": "2012-04-09 21:00:08 UTC"
},
etc.
]
}https://stackoverflow.com/questions/23745426
复制相似问题