Rails从JSON数组中选择

时间:2012-09-26 05:54:39

标签: ruby-on-rails ruby json foursquare

我有一个从Foursquare返回的JSON数组;我们称之为@venues。我希望能够选择"通过下拉框的场地,我希望它成为表格的一部分。

这意味着我希望能够按名称选择特定场所(即本例中的Hotel Utah Saloon),并将其id保存到模型中。为了澄清,我只会保存我选择的场地,而不是所有场地。

通过研究,我发现自己在selectcollection_selectselect_tag之间感到困惑。请记住,这是直接来自JSON.parse方法的JSON,而不是数据库模型。

如何在表单中创建此下拉列表?

为了澄清,@venues看起来像这样:

[
            {
               "beenHere":8,
               "venue":{
                  "id":"3fd66200f964a52023f11ee3",
                  "name":"Hotel Utah Saloon",
                  "contact":{
                     "phone":"4155466300",
                     "formattedPhone":"(415) 546-6300",
                     "twitter":"hotelutah"
                  },
                  "location":{
                     "address":"500 4th St",
                     "crossStreet":"Corner of Bryant",
                     "lat":37.77947007181946,
                     "lng":-122.39816943501836,
                     "postalCode":"94107",
                     "city":"San Francisco",
                     "state":"CA",
                     "country":"United States",
                     "cc":"US"
                  },
                  "categories":[
                     {
                        "id":"4bf58dd8d48988d1e9931735",
                        "name":"Rock Club",
                        "pluralName":"Rock Clubs",
                        "shortName":"Rock Club",
                        "icon":"https:\/\/foursquare.com\/img\/categories\/arts_entertainment\/musicvenue_rockclub.png",
                        "parents":[
                           "Arts & Entertainment",
                           "Music Venues"
                        ],
                        "primary":true
                     }
                  ],
                  "verified":true,
                  "stats":{
                     "checkinsCount":6654,
                     "usersCount":3330,
                     "tipCount":50
                  },
                  "likes":{
                     "count":0,
                     "groups":[

                     ]
                  },
                  "beenHere":{
                     "count":0
                  }
               }
            }
        ]

1 个答案:

答案 0 :(得分:1)

控制器

@venues = JSON.parse @venues

查看

<%= select(:model, :venue_id, @venues.map {|v| [ v['venue']['name'], v['venue']['id'] ] }) %>

或者更清洁:

控制器

@venues = JSON.parse @venues
@venues_list = @venues.map { |v| v['venue'] }

查看

<%= select(:model, :venue_id, @venues_list.map {|v| [ v['name'], v['id'] ] }) %>

有关select helper的更多信息。