您可以使用has_many_through 关联,大致如下:
class Bill < ActiveRecord::Base
has_many :sponsorships, -> { where(kind: :primary) }, class_name: "Sponsorship"
has_many :cosponsorships, -> { where(kind: :secondary) }, class_name: "Sponsorship"
has_many :sponsors, class_name: 'CongressPerson', through: :sponsorships
has_many :cosponsors, class_name: 'CongressPerson', through: :cosponsorships
end
class Sponsorship < ActiveRecord::Base
# schema bill_id(INT), sponsor_id(INT), kind(STRING)
belongs_to :bill
belongs_to :sponsor, class_name: "CongressPerson"
end
class CongressPerson < ActiveRecord::Base
has_many :sponsorships, -> { where(kind: :primary) }, class_name: "Sponsorship", foreign_key: :sponsor_id
has_many :cosponsorships, -> { where(kind: :secondary) }, class_name: "Sponsorship", foreign_key: :sponsor_id
has_many :sponsored_bills, through: :sponsorships, source: :bill
has_many :cosponsored_bills, through: :cosponsorships, source: :bill
end
这是Sponsorship 表的基本迁移:
class CreateSponsorships < ActiveRecord::Migration
def change
create_table :sponsorships do |t|
t.references :bill
t.references :sponsor
t.string :kind
t.timestamps
end
end
end
这将允许您进行如下调用:
@bill.sponsors
# => returns the congress_people sponsoring the bill
@bill.cosponsors
# => returns the congress_people cosponsoring the bill
@congress_person.sponsored_bills
# => returns the bills sponsored by the congress person
@congress_person.cosponsored_bills
# => returns the bills cosponsored by the congress person
然后在您的CongressPerson 显示视图中:
<%= @congress_person.sponsored_bills.each do |sponsored| %>
# populate your HTML table row
<% end %>
<%= @congress_person.cosponsored_bills.each do |cosponsored| %>
# populate your HTML table row
<% end %>