1

I am trying to add to a many to many relationship with the following models:

class Account < ApplicationRecord
  belongs_to :user
  has_many :issues, through: :interests
end

class Issue < ApplicationRecord
  has_many :accounts, through: :interests
end

class Interest < ApplicationRecord
  belongs_to :account
  belongs_to :issue
end

When I try to call the following method in my accounts_controller

def add_issue
  issue = Issue.find(params[:id])
  @account = current_user.account
  @account.interests.create(issue: issue)
end

I get an error reading undefined method 'interests' for #<Account:0x007fe50e23b658>. What is the proper way to go about posting to a join table?

Pavan
  • 33,316
  • 7
  • 50
  • 76
d00medman
  • 191
  • 3
  • 15

1 Answers1

2

undefined method 'interests' for #<Account:0x007fe50e23b658>

You need to add the association has_many :interests as well in the models

class Account < ApplicationRecord
  belongs_to :user
  has_many :interests
  has_many :issues, through: :interests
end

class Issue < ApplicationRecord
  has_many :interests
  has_many :accounts, through: :interests
end

I suggest you to read HMT association

Pavan
  • 33,316
  • 7
  • 50
  • 76
  • This was the missing piece. So if I want to leverage any many-to-many relationship, I also need to specify that there is a relationship with the join table itself? – d00medman Jul 22 '17 at 17:36
  • @d00medman With the `has_many :trough`, that is how it should be. With `has_and_belongs_to_many` the things are slightly different :) – Pavan Jul 22 '17 at 17:39