Rails: Overriding ActiveRecord association method Rails: Overriding ActiveRecord association method ruby ruby

Rails: Overriding ActiveRecord association method


You can use block with has_many to extend your association with methods. See comment "Use a block to extend your associations" here.
Overriding existing methods also works, don't know whether it is a good idea however.

  has_many :tags, :through => :taggings, :order => :name do    def << (value)      "overriden" #your code here      super value    end       end


If you want to access the model itself in Rails 3.2 you should use proxy_association.owner

Example:

class Author < ActiveRecord::Base  has_many :books do    def << (book)      proxy_association.owner.add_book(book)    end  end  def add_book (book)    # do your thing here.  endend

See documentation


I think you wanted def tags.<<(*new_tags) for the signature, which should work, or the following which is equivalent and a bit cleaner if you need to override multiple methods.

class << tags  def <<(*new_tags)    # rawr!  endend