Ruby on rails 使用符号输入调用类方法
我有一个类方法:Ruby on rails 使用符号输入调用类方法,ruby-on-rails,class,hash,class-method,Ruby On Rails,Class,Hash,Class Method,我有一个类方法: class CountryCodes def self.country_codes { AF: "Afghanistan", AL: "Albania", ... } end end 我有一个rake任务,创建一个城市,带有一个类似“AF”的国家代码。我希望它通过调用类方法并引用键值对,将“AF”替换为“Afghanistan” 将国家/地区代码设置为“AF”的当前功能是: 我可以通过调用put CountryCodes.country\u c
class CountryCodes
def self.country_codes
{ AF: "Afghanistan",
AL: "Albania",
... }
end
end
我有一个rake任务,创建一个城市,带有一个类似“AF”的国家代码。我希望它通过调用类方法并引用键值对,将“AF”替换为“Afghanistan”
将国家/地区代码设置为“AF”的当前功能是:
我可以通过调用put CountryCodes.country\u codes[:AF]
手动检索“阿富汗”。通过结合这些策略,我(错误地)认为我可以:
city = City.create do |c|
c.name = row[:name]
c.country_code = CountryCodes.country_code[:row[:country_code]] #obviously, this failed
end
运行此操作时发生的故障是:
雷克流产了!
TypeError:没有将符号隐式转换为整数
如何正确调用动态输入为
行[:country\u code]
的CountryCodes.country\u code
类方法?由于CountryCodes.country\u code
有一个符号散列,因此在引用它时需要调用一个符号。例如:country\u code[“AF”]
与country\u code[:AF]
不同
若要更正此问题,请使用Ruby的To-sym将字符串行[:country\u code]
转换为符号:
city = City.create do |c|
c.name = row[:name]
c.country_code = CountryCodes.country_code[row[:country_code].to_sym] # < .to_sym
end
city=city.create do|c|
c、 名称=行[:名称]
c、 国家/地区代码=国家/地区代码。国家/地区代码[行[:国家/地区代码]。\
结束
因为我看不到您的模式,所以我的回答也假设国家代码
是城市
模型中的字符串(不是整数)。严肃的回答:
使用国家代码Gem!
I18n准备就绪,不管怎样它到底是如何失败的?看起来您正在编写:row[:country\u code]
,这将失败,因为符号:row
不是您想要的变量row
。我已将出现的错误添加到问题中。如何修复您所指的错误?类型为text
!希望这不会改变什么。文本也可以。只要它不需要整数。让我知道这是否适用于您,或者如果您遇到另一个错误。您以前使用过这些吗?
city = City.create do |c|
c.name = row[:name]
c.country_code = CountryCodes.country_code[row[:country_code].to_sym] # < .to_sym
end