Long live push_with_attributes

January 12th, 2007

Posted by Steve Butterworth

So the general rule tends to be as soon as you have has_and_belongs_to_many associations and you want to use push_with_attributes then you are probably missing a join model. has_many :through has made it easy for us to promote our join tables to join models so we now have power in our joins. But although at a glance it looks simple you soon find that out of the box you loose a lot of functionality converting has_and_belongs_to_many associations to has_many :through associations. For a start we have no push_with_attributes anymore which was kind of the reason we went this route in the first place.

Well there's no need to panic. We can add our beloved push_with_attributes function back onto our association just like this...

  has_many :albums, :through => :artist do
    def push_with_attributes(album, join_attrs)
      Artist.with_scope(:create => join_attrs) { self << album}
    end
  end

Now adding this to all the necessary :through associations doesn't seem very dry so what we can do is use the power of Ruby meta programming and extend ActiveRecord's through functionality to include this out of the box.

Sorry, comments are closed for this article.