开发者

ActiveModel::Naming attributes definition

I'm working on a rails3 app and开发者_StackOverflow中文版 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.


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.


Not exactly.

MyClass.all call a SOAP API and return a hash of object.

What I wanted to do was to convert hash['key'] to hash.key. After doing this whith my own method I've used this Gem that saved my life.

Hope that helps someone :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜