Rails - 如何与 class_name 建立 has_many_through 关联
Rails - how to set up a has_many_through association with class_name
我正在修改一个包含发起人和成员的应用程序,并希望添加一个关联,这样发起人可以拥有许多可能是成员的联系人。会员可以是许多赞助商的联系人。这会是 has_many 直通关系,联系人使用成员 class 吗?这是我试过的。
class Sponsor < ActiveRecord::Base
has_many :member_contacts
has_many :contacts, through: member_contacts, class_name: :member
end
class Contact < ActiveRecord::Base
has_many :member_contacts
has_many :sponsors, through: member_contacts
end
class MemberContact < ActiveRecord::Base
belongs_to :contact
belongs_to :sponsor
end
class Member < ActiveRecord::Base
has_many :subscriptions
has_many :groups, through: :subscriptions
has_many :member_notes
has_many :chapters, -> { uniq }, through: :groups
has_many :announcements, -> { uniq }, through: :groups
validates_uniqueness_of :email
end
sponsors_controller.rb
class SponsorsController < ApplicationController
def index
@sponsors = Sponsor.joins(:sponsor_sessions).all
end
def new
@sponsor = Sponsor.new
@sponsor.contacts.build
end
end
并在 form.html.haml
= f.collection_select :contacts, Member.all, :id, :full_name, { selected: @sponsor.contacts.map(&:id) }, { multiple: true }
当我尝试访问 /sponsors/new 时,我得到
'uninitialized constant Sponsor::member'
指向 sponsors_controller 新方法中的行
@sponsor.contacts.build
谁能告诉我我做错了什么?
问题出在您的 Sponsor
模型中的这一行
has_many :contacts, through: member_contacts, class_name: :member
应该是
has_many :contacts, through: member_contacts, class_name: 'Member'
我正在修改一个包含发起人和成员的应用程序,并希望添加一个关联,这样发起人可以拥有许多可能是成员的联系人。会员可以是许多赞助商的联系人。这会是 has_many 直通关系,联系人使用成员 class 吗?这是我试过的。
class Sponsor < ActiveRecord::Base
has_many :member_contacts
has_many :contacts, through: member_contacts, class_name: :member
end
class Contact < ActiveRecord::Base
has_many :member_contacts
has_many :sponsors, through: member_contacts
end
class MemberContact < ActiveRecord::Base
belongs_to :contact
belongs_to :sponsor
end
class Member < ActiveRecord::Base
has_many :subscriptions
has_many :groups, through: :subscriptions
has_many :member_notes
has_many :chapters, -> { uniq }, through: :groups
has_many :announcements, -> { uniq }, through: :groups
validates_uniqueness_of :email
end
sponsors_controller.rb
class SponsorsController < ApplicationController
def index
@sponsors = Sponsor.joins(:sponsor_sessions).all
end
def new
@sponsor = Sponsor.new
@sponsor.contacts.build
end
end
并在 form.html.haml
= f.collection_select :contacts, Member.all, :id, :full_name, { selected: @sponsor.contacts.map(&:id) }, { multiple: true }
当我尝试访问 /sponsors/new 时,我得到
'uninitialized constant Sponsor::member'
指向 sponsors_controller 新方法中的行
@sponsor.contacts.build
谁能告诉我我做错了什么?
问题出在您的 Sponsor
模型中的这一行
has_many :contacts, through: member_contacts, class_name: :member
应该是
has_many :contacts, through: member_contacts, class_name: 'Member'