【问题标题】:Jbuilder Build Multidimensional ArrayJbuilder构建多维数组
【发布时间】:2014-07-07 20:48:00
【问题描述】:

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

在我的模型中,每个 'Venue' 都有_many 'Venue_Images'。正如预期的那样,上面的 JSON 为我提供了主场地数组中的场地图像对象数组。

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 视图中不可用。我需要将这些 url 放入 @venues 数组而不是回形针对象的所有其他属性中,这样我就可以在 JS 中遍历它们并在我的视图中显示它们。

最好的方法是什么?我尝试了几个不同的块并查看了 jbuilder wiki 和几篇文章,但没有任何工作。

谢谢

【问题讨论】:

    标签: ruby-on-rails arrays jbuilder


    【解决方案1】:

    如果我的理解正确,你的想法是这样吗:

    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.
      ]
    }
    

    【讨论】:

    • 谢谢,让我今天早上试一试,然后回来找你!
    猜你喜欢
    • 1970-01-01
    • 2020-07-16
    • 2017-02-24
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多