A Little Helper To Help You :through
Join the DZone community and get the full member experience.
Join For FreeDo 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
# many_to_many_through PartyContectMech, Party, ContectMech returns:
# Party.has_many :party_contact_meches, :foreign_key => :party_id
# Party.has_many :contact_meches, :through => :party_contact_meches, :foreign_key => :party_id
#
# ContactMech.has_many :party_contact_meches, :foreign_key => :contact_mech_id
# ContactMech.has_many :parties, :through => :party_contact_meches, :foreign_key => :contact_mech_id
#
# PartyContactMech.belongs_to :party
# PartyContactMech.belongs_to :contact_mech
#
# evaluating the result defines the necessary 6 relations,
# * save some typing,
# * no need to jump between the 3 source files,
# * less chance for typo and/or human mistake
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
Opinions expressed by DZone contributors are their own.
Comments