ActiveModel::命名属性定义
我正在开发一个rails3应用程序,我对活动模型有点困惑。 这是我的模型:
class MyClass
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :foo, :foo1, foo2
def initialize(attributes = {})
attributes.each { |key, value| send "#{key}=", value }
end
def self.all
get_elig
end
private
def self.get_elig
# My function
end
end
get_elig
函数返回一个像这样的哈希: {"foo1"=>"bar1", "foo2"=>"bar2", "foo"= >"bar"}
在 Rails 控制台下:
irb(main):031:0> t = MyClass.all
=> {"foo1"=>"bar1", "foo2"=>"bar2", "foo"=>"bar"}
irb(main):032:0> t.foo
NoMethodError: undefined method `foo' for #<Hash:0x105e96be0>
我的问题很简单:我的模型出了什么问题?
感谢您的帮助。
I'm working on a rails3 app and I'm a little bit confused with Active Model.
Here is my model :
class MyClass
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :foo, :foo1, foo2
def initialize(attributes = {})
attributes.each { |key, value| send "#{key}=", value }
end
def self.all
get_elig
end
private
def self.get_elig
# My function
end
end
The get_elig
function return a Hash like this one : {"foo1"=>"bar1", "foo2"=>"bar2", "foo"=>"bar"}
Under the rails console :
irb(main):031:0> t = MyClass.all
=> {"foo1"=>"bar1", "foo2"=>"bar2", "foo"=>"bar"}
irb(main):032:0> t.foo
NoMethodError: undefined method `foo' for #<Hash:0x105e96be0>
My question is simple : what was going wrong with my model ?
Thanks for help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您所说: MyClass.all 返回一个哈希对象,并且您不能在哈希上使用点表示法。
您可能想要的是使用哈希值初始化您的类:x = MyClass.new({"foo1" => "bar1"})。现在您可以按照实现的建议使用点表示法进行访问。
As you said: MyClass.all returns a hash object and you can not use dot notation on a hash.
What you probably want is to initialize your class with the hash: x = MyClass.new({"foo1" => "bar1"}). Now you have access with dot notation as the implementation suggests.
不完全是。
MyClass.all 调用 SOAP API 并返回对象的哈希值。
我想做的是将
hash['key']
转换为hash.key
。在用我自己的方法完成此操作后,我使用了这个拯救了我生命的 Gem 。希望对某人有帮助:)
Not exactly.
MyClass.all call a SOAP API and return a hash of object.
What I wanted to do was to convert
hash['key']
tohash.key
. After doing this whith my own method I've used this Gem that saved my life.Hope that helps someone :)