我有一张叫做账单的桌子。法案有多个赞助商和多个共同赞助商。赞助商和共同赞助商都包含一份国会议员名单。我还有一张叫做congress_people的桌子。在congress_people显示页面上,我想显示一张表格,其中显示了国会议员赞助的票据以及显示他们共同发行的票据的票据。有关如何做到这一点的任何想法?我知道生成表格,但我不知道如何设置关联。我正在使用rails 4.2和mysql2。感谢
答案 0 :(得分:0)
您可以使用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 %>