Do you have to code a lot of "has_many :through" relation models in your Rails application? Here is a little helper that will help you DRY. It is very simple indeed, for an example here are the models:
Party, ContectMech and PartyContectMech(the join model).
Call many_to_many_through, perhaps in your application.rb
eval many_to_many_through(PartyContectMech, Party, ContectMech)
SOURCE:
def many_to_many_through(through_model, model1, model2)
through_table = through_model.table_name
table1 = model1.table_name
table2 = model2.table_name
model1_id = model1.name.underscore + "_id"
model2_id = model2.name.underscore + "_id"
%Q{
#{model1}.has_many :#{through_table}, :foreign_key => :#{model1_id}
#{model1}.has_many :#{table2}, :through => :#{through_table}, :foreign_key => :#{model1_id}
#{model2}.has_many :#{through_table}, :foreign_key => :#{model2_id}
#{model2}.has_many :#{table1}, :through => :#{through_table}, :foreign_key => :#{model2_id}
#{through_model}.belongs_to :#{model1.name.underscore}
#{through_model}.belongs_to :#{model2.name.underscore}
}
end