attr_accessor, not able to access property

后端 未结 4 1622
旧巷少年郎
旧巷少年郎 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:50

    Looks like group_id is already a property on your Foo object (shown by the fact that it returns 106 when attr_accessor is omitted). By adding attr_accessor you are overriding what's already there and creating a method reader and writer called group_id. The return of the newly defined group_id is nil since you don't define anything.

    Conceptually, you're ending up with something like this:

    class Foo < ActiveRecord::Base
      def group_id  # overriding previous definition of 'group_id'
        nil
      end
    end
    


    Edit:

    If your goal is expose properties then yes, use attr_accessible

提交回复
热议问题