attr_accessor, not able to access property

后端 未结 4 1624
旧巷少年郎
旧巷少年郎 2021-01-23 10:29

This is probably very stupid question but here we go

class Foo < ActiveRecord::Base
 attr_accessor :group_id
end

From irb

4条回答
  •  逝去的感伤
    2021-01-23 10:44

    Without the accessor, for sure you have a 'belongs_to :group' in your Foo model, so if you call 'group_id' to an instance of 'Foo' you will get the value of this field.

    For instance, if you set an accessor called like that attribute( group_id) it will overwrite the original field and it will return nil, if haven´t assigned any value.

    class Foo < ActiveRecord::Base
      attr_accessor :group_id
    end
    
    # gets record which has group_id set to 106    
    foo = Foo.find(1)
    foo.group_id
    => nil
    foo.group_id = "wadus"
    => "wadus"
    foo.group_id
    => "wadus"
    

提交回复
热议问题