Using attr_accessor and attr_accessible on the same field

前端 未结 4 1814
误落风尘
误落风尘 2020-12-01 06:42

What happens in the background with the following code?

class User < ActiveRecord::Base

 attr_accessor :name
 attr_accessible :name

end
<
4条回答
  •  [愿得一人]
    2020-12-01 07:12

    Thanks everyone for quick answers! Your answers combined gave me the pieces I needed to understand this puzzle, I think.

    (In a related problem, I was getting a lot of nil errors like "Object doesn’t support #inspect", and "undefined method ‘keys’ for nil:NilClass". I managed to solve it now, by removing the att_accessor field altogether.)

    By experimenting with this particular case, this is what I've found out:

    Actually, the :name field won't be persisted to the database.

    user = User.new(:name=>"somename")
    

    Will only set the attribute on the object, but not persist the :name column to the database. Like the following 'rails console' output shows:

    > user
    => 
    > user.save
    => true
    > user
    => 
    

    I assume this is because *the setter made by attr_accessor will override ActiveRecord's setter* (which takes care of the database persistence). You can still retrieve the value from the :name field from the object though, like this:

    > user.name
    => "somename"
    

    So, in conclusion, I've learnt that using attr_accessor on fields might lead to them not being persisted to the database. And while I thought attr_accessible describes fields in the database that should be accessible from the outside, it doesn't seem to make a difference in this case.

提交回复
热议问题