When using a belongs_to (or any association type for that matter) how do
you assign the associated object?
Example:
Employee belongs to a Company
do you do this:
e = Employee.new
e.company_id = 12
or
e = Employee.new
e.company = Company.find(12)
I find the latter more reliable when using validates_presence_of or when
doing some custom validation that involves querying the Company. In fact
I would like to make it the only way to assign association. I guess I
could protect company_id from being set outside its class.
When using a belongs_to (or any association type for that matter) how do
you assign the associated object?
Example:
Employee belongs to a Company
do you do this:
e = Employee.new
e.company_id = 12
or
e = Employee.new
e.company = Company.find(12)
Definitely the second. You’re correct in finding it more reliable. But
also, it’s a practice belonging to a larger principle: code to an
interface, not an implementation.
By accessing e.company_id you’re violating its encapsulation barrier.
(In other words, you’re poking around in its internals, when you should
ask the object in question to do it for you.)
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.