Understanding Ruby on Rails ActiveRecord Model Components

My model, "DataFile", has a bunch of fields that I would like to set from outside the model, for example.

file = DataFile.new
file.owner = 123

Now, as far as I know, I would have to put "attr_accessor: field" in my model for each field that I would like to change externally. However, the above code works fine without specifying any attr_accessors, setting the owner field to 123. Why is this?

I was expecting to get a "method not defined" error or something.

+2


source to share


3 answers


Since the Rails ORM uses the ActiveRecord template, two methods are automatically generated for each column in the database associated with this table: columnname and columnname =. This happens automatically as a result of your model inheriting from ActiveRecord :: Base. These methods are defined using ruby ​​metaprogramming facilities and are dynamically created during class creation.



For more information on what's going on, I would look at the Rails source. However, the above is probably enough to give you a working idea of ​​what's going on.

+11


source


Drew and Zepplock got it right, but I'll just add one more thing. The accessors that Rails (actually ActiveRecord) creates for database fields are not Ruby accessors, and if you use script / console, you will see that the owner is not an object file instance variable.

You will probably never notice this until you move away from the standard accessories and try to manipulate @owner inside a method in a file. If you are learning Ruby at the same time, you are learning Rails (which is what I did), you will probably run into this at some point. This is why you need to write:

class MyClass < ActiveRecord::Base
  def invalidate_owner
    self.owner = owner << " no longer owns this"
    save
  end
end

      



instead

class MyClass < ActiveRecord::Base
  def invalidate_owner
    self.owner << " no longer owns this"
    save
  end
end

      

+1


source


Most likely the "owner" is part of your database model. Accessors for database fields are automatically generated for you.

0


source







All Articles