Is there a way to override one of the methods provided by an ActiveRecord association?
Say for example I have the following typical polymorphic has_many :through association:
class Story < ActiveRecord::Base has_many :taggings, :as => :taggable has_many :tags, :through => :taggings, :order => :name end class Tag < ActiveRecord::Base has_many :taggings, :dependent => :destroy has_many :stories, :through => :taggings, :source => :taggable, :source_type => "Story" end
As you probably know this adds a whole slew of associated methods to the Story model like tags, tags<<, tags=, tags.empty?, etc.
How do I go about overriding one of these methods? Specifically the tags<< method. It's pretty easy to override a normal class methods but I can't seem to find any information on how to override association methods. Doing something like
def tags<< *new_tags #do stuff end
produces a syntax error when it's called so it's obviously not that simple.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With