Question

I am planning to use conditional validations along the lines of what is described in this railscast In the railscast, which is rather old, attr_accessor is used, (skip to the later portion of the video to see the code). I am relatively new to rails programming and wanted to read up on what attr_accessor does. This post asks about using it and the most upvoted answer says that they should hardly ever be used in rails.

Is it necessary/should I be using attr_accessor like is done in the railscast? Or are these methods automatically created? Is there any danger to using attr_accessor in this case?

Was it helpful?

Solution

Using attr_accessor has nothing to do with Active Record. I discuss how it works in this post, that is also related to AR.

Now, what AR does do, is it automatically creates is own "accessor" methods (e.g. x/x=) based on the database model. These automatically created methods are really just stubs that it uses to proxy into the internal AR workings.

The point is, attr_accessor (automatically) wraps simple instance variable access, while AR (automatically) created methods wrap AR magic. The two operations are mutually exclusive. Because attr_accessor does not "link to" the AR magic, all it can be used for creating transient fields which are not persisted: AR does not know of or care about instance variables.

The "danger" comes from perhaps complicating the model objects with transient information -- if it is transient, why should it be part of a model object? This is the argument the most up-voted answer in the linked question makes.

Happy coding.


However, I do no know what would happen if using attr_accessor for the same field as that which happens to be in the AR model... confusion at the least.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top