如何在Rails 3中显示has_many关联的属性?

时间:2011-06-17 05:41:36

标签: ruby-on-rails associations has-many

我有一个has_many广告系列的联系人。

广告系列有很多联系人。

但是,联系人可能具有start_date和每个广告系列的状态。

例如:

 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

感谢。

1 个答案:

答案 0 :(得分:5)

has_many :through允许您在连接表上定义与关系本身相关的属性。

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

通常,您只需将外键添加到连接表中即可。但您也可以添加其他列:

t.integer :contact_id
t.integer :campaign_id
t.date    :start_date
t.status  :string # 'active','stopped'

现在您可以为关系指定属性:

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)