【发布时间】:2016-01-01 22:23:34
【问题描述】:
我正在尝试在 Rails 4 中制作应用程序。我对表单使用简单的表单,对国家/地区列表使用 country_select gem。
我有一个地址模型,其中包括这个方法:
def country_name
self.country = ISO3166::Country[country]
country.translations[I18n.locale.to_s] || country.name
end
当我尝试保存新地址时,我收到此错误:
undefined method `translations' for "Australia":String
谁能看出这个方法定义有什么问题?
如果我将视图更改为:
<% if @profile.addresses.any? %>
<%= @profile.addresses.first.country.titlecase %>
<% else %>
<span class="profileeditlink">
<%= link_to "Add your location", new_address_path %>
</span>
<% end %>
然后记录显示 - 但显示为 AU 而不是澳大利亚(这是地址模型中的方法提供的)。
地址表:
create_table "addresses", force: :cascade do |t|
t.string "unit"
t.string "building"
t.string "street_number"
t.string "street"
t.string "city"
t.string "region"
t.string "zip"
t.string "country"
t.boolean "main_address"
t.boolean "project_offsite"
t.string "time_zone"
t.float "latitude"
t.float "longitude"
t.integer "addressable_id"
t.integer "addressable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "addresses", ["addressable_type", "addressable_id"], name: "index_addresses_on_addressable_type_and_addressable_id", unique: true, using: :btree
接受在铉的建议,
我将地址模型中的国家名称方法更改为:
def country_name
# self.country = ISO3166::Country(country)
# country.translations[I18n.locale.to_s] || country.name
iso_country = ISO3166::Country.find_by_name[country] # `country` should be name like 'Australia'
iso_country.translations[I18n.locale.to_s] || iso_country.name
end
我收到此错误:
undefined method `translations' for nil:NilClass
另一个尝试:
我尝试将表单输入更改为:
<%= f.country_select :country, priority: [ "Australia", "New Zealand", "United Kingdom" ] %>
它仍然只显示国家代码而不是国家名称。我被卡住了。
另一个尝试
我发现了这个帖子: Rails Simple_Form: How to show long name of the country
这篇文章中的答案建议将 country_name 定义为:
def country_name
country = ISO3166::Country[country_code]
country.translations[I18n.locale.to_s] || country.name
end
这与我之前的尝试略有不同,但是,当我尝试这个时,我得到了这个错误:
undefined local variable or method `country_code' for #<Address:0x007fbae5bfb290>
我尝试将方法更改为:
def country_name
self.country = ISO3166::Country[country_code]
country.translations[I18n.locale.to_s] || country.name
end
这给出了与不使用“self”的公式相同的错误。我认为这些尝试不起作用,因为我的地址表中的属性称为“国家”。
当我将方法更改为:
def country_name
self.country = ISO3166::Country[country]
country.translations[I18n.locale.to_s] || country.name
end
我收到“翻译”一词的错误。当我从方法中删除 '.translations' 时,我收到一个包含单词 'name' 的错误。
我正在失去理智试图弄清楚这一点。
另一个尝试
我尝试将国家 gem 添加到我的 gem 文件中(在 country_select 上方)。
当我捆绑这个 gem 时没有任何变化。同样的问题。
另一个尝试
再试一次(因为我最初定义了方法),但安装了国家 gem(在 country_select gem 之上):
def country_name
self.country = ISO3166::Country[country]
country.translations[I18n.locale.to_s] || country.name
end
我收到此错误:“开曼群岛”的未定义方法“翻译”:字符串
这与我最初开始时遇到的问题相同,因此我认为添加国家/地区 gem 并没有帮助解决问题。
【问题讨论】:
-
是
ISO3166::Country来自github.com/hexorx/countries 吗? -
否 - 国家选择宝石:github.com/stefanpenner/country_select
-
对,但是
country_select依赖于countries。 -
不确定你在问我什么。国家选择处理交互
标签: ruby-on-rails simple-form country-codes