Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Overriding ActiveRecord association method

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.

like image 282
seaneshbaugh Avatar asked May 23 '10 05:05

seaneshbaugh


1 Answers

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 
like image 111
Voyta Avatar answered Oct 08 '22 01:10

Voyta