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
在我的模型中,每个“ field ”都有很多“ field 图像”。正如预期的那样,上面的 JSON 为我提供了主 field 数组中的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 代码中的 field 图像,以便我可以在它们上调用 Paperclip/S3 助手(即 .image.url(:medium)),因为这些在 JS View 中不可用。我需要将这些 url 放入 @venues 数组中,而不是回形针对象的所有其他属性中,这样我就可以在 JS 中迭代它们并在我的 View 中显示它们。
最好的方法是什么?我尝试了几个不同的 block ,并查看了 jbuilder wiki 和几篇文章,但没有任何效果。
谢谢
最佳答案
如果我没理解错的话,你的想法是这样的:
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.
]
}
关于ruby-on-rails - Jbuilder 构建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23745426/