margo
margo

Reputation: 2927

Rails - how to set up a has_many_through association with class_name

I'm amending an application which has sponsors and members and want to add an association whereby sponsors can have many contacts which may be members. Members can be a contact for many sponsors. Would this be a has_many through relationship, where the contact uses the member class? Here's what I've tried.

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

and in form.html.haml

= f.collection_select :contacts, Member.all, :id, :full_name, { selected: @sponsor.contacts.map(&:id) }, { multiple: true }

When I try to visit /sponsors/new I get

'uninitialized constant Sponsor::member' 

pointing to the line in sponsors_controller new method

@sponsor.contacts.build

Can anyone let me know what I'm doing wrong?

Upvotes: 1

Views: 24

Answers (1)

Pavan
Pavan

Reputation: 33542

The problem would be this line in your Sponsor model

has_many :contacts, through: member_contacts, class_name: :member

Which should be

has_many :contacts, through: member_contacts, class_name: 'Member'

Upvotes: 1

Related Questions