I have a Contact which has_many Campaigns.
And a Campaign has_many Contacts开发者_如何转开发.
However, a Contact may have a start_date and a status for each Campaign.
For Example:
Contact A is active and start_date = 4/4/11 for Campaign 1
Contact A is stopped and start_date = 3/2/11 for Campaign 1
Thanks.
has_many :through
lets you define attributes on the join table which pertain to the relationship itself.
class Contact
has_many :campaign_contacts
has_many :campaigns, :through => :campaign_contacts
end
class CampaignContact
belongs_to :contact
belongs_to :campaign
end
class Campaign
has_many :campaign_contacts
has_many :contacts, :through => :campaign_contacts
end
Normally you would just add the foreign keys to the join table and be done with it. But you can also add other columns:
t.integer :contact_id
t.integer :campaign_id
t.date :start_date
t.status :string # 'active','stopped'
Now you can assign the attributes to the relationship:
campaign1 = Campaign.find(1)
campaign2 = Campaign.find(2)
contactA = Contact.find_by_name("A")
contactA.campaign_contacts.build(:status=>'active',
:start_date => '2011-04-04',:campaign=>campaign1)
contactA.campaign_contacts.build(:status=>'stopped',
:start_date => '2011-03-02',:campaign=>campaign1)
精彩评论