:name方法表示不存在于collection_select中

时间:2013-08-17 16:14:05

标签: ruby-on-rails

我在Rails应用程序中安装了countries gem,并希望像这样创建一个集合选择

  <%= f.collection_select :country, Country.all, :id, :name %>

但它给了我这个错误(对于第一个国家)。

undefined method `name' for ["Andorra", "AD"]:Array.

如果我在控制台中使用此gem执行Country.all,则会创建一系列像这样的国家

Country.all

=> [["Andorra", "AD"], ["United Arab Emirates", "AE"], ["Afghanistan", "AF"], ["Antigua and Barbuda", "AG"], ["Anguilla", "AI"], ["Albania", "AL"], ["Armenia", "AM"], ["Netherlands Antilles", "AN"], ["Angola", "AO"], ["Antarctica", "AQ"], ["Argentina", "AR"], ["American Samoa", "AS"], ["Austria", "AT"], ["Australia", "AU"], ["Aruba", "AW"], ["Åland Islands", "AX"], ["Azerbaijan", "AZ"], 

如果我创建一个像这样的国家的实例传递它的两个字母代码

>> c = Country.new('US')

然后我可以获得名称方法

>> c.name
=> "United States"

我正在尝试使用countries gem,因为我无法弄清楚如何使用countries_select gem创建一个集合select。如果你不能告诉我如何解决国家宝石的问题,那么请告诉我如何使用countries_select gem。

1 个答案:

答案 0 :(得分:0)

您可以安装gem'country_select'以提供呈现select标记的帮助程序。 您传递模型和属性名称,并呈现选择框。如果您有用户模型和国家/地区属性,请写

<%= country_select(:user, :country) %>

它会产生

<select id="user_country" name="user[country]"><option value="Afghanistan">Afghanistan</option>
<option value="Åland Islands">Åland Islands</option>
<option value="Albania">Albania</option>
....
</select>

https://github.com/hexorx/countries

https://github.com/stefanpenner/country_select