0

我在 Rails 应用程序中安装了国家 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_select宝石创建集合选择。如果您不能告诉我如何解决国家宝石的问题,那么请让我知道如何使用国家选择宝石。

4

1 回答 1

0

您可以安装 gem 'country_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

于 2013-08-17T18:16:50.373 回答