Call AR belongs_to association accessor ID method on object assignment

Hi,

Haven’t been able to find this raised before but I’m sure it must have
been. When assigning an object to a belongs_to association I would
like it to call the association_id= method instead of directly
updating the attributes array. This is because I want to modify the
behaviour when assigning a particular object without writing separate
methods for whether it’s just an ID being assigned or a full object.

Example:
a = Author.find(2)
b = Book.new
b.author = a # Should call b.author_id=(val)

Is there already a simple way to achieve this? (without having to run
validation)

Changing it would be a one-line patch, but can anyone think of
problems this would introduce?

Thanks,
Andrew

On Aug 10, 4:40 am, Andrew F. [email protected] wrote:

Hi,

Haven’t been able to find this raised before but I’m sure it must have
been. When assigning an object to a belongs_to association I would
like it to call the association_id= method instead of directly
updating the attributes array. This is because I want to modify the
behaviour when assigning a particular object without writing separate
methods for whether it’s just an ID being assigned or a full object.

There’s a ticket on lighthouse about this, I seem to recall there’s a
patch too.

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs