Search code examples
ruby-on-railsrubyactiverecordmodelattr-accessor

Understanding Ruby on Rails ActiveRecord model Accessors


My Model, "DataFile", has a bunch of fields which I'd like to set from outside the Model, e.g.

file = DataFile.new
file.owner = 123

Now, as far as I know, I'd have to place an "attr_accessor :field" in my model, for every field that I'd like to modify from outside. However, the above code runs fine without having any attr_accessors defined, setting the owner field to 123. Why is that?

I'd expected to get a "method not defined" error or something like that.


Solution

  • Because Rails' ORM uses the ActiveRecord pattern, two methods are created automatically for each column in the database associated with that table: columnname, and columnname=. This happens "automatically" as a result of your model inheriting from ActiveRecord::Base. These methods are defined using ruby's metaprogramming facilities and are created dynamically at the time of class creation.

    For more info as to exactly what's going on, I would take a look at the Rails source. However, the above is probably enough to give you a working understanding of what is happening.