如何 post 在 rails 控制器中加入 table

How to post to a join table in a rails controller

我正在尝试添加与以下模型的多对多关系:

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

当我尝试在 accounts_controller

中调用以下方法时
def add_issue
  issue = Issue.find(params[:id])
  @account = current_user.account
  @account.interests.create(issue: issue)
end

我在读取 undefined method 'interests' for #<Account:0x007fe50e23b658> 时出错。发布到加入的正确方法是什么 table?

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

您还需要在模型中添加关联 has_many :interests

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

我建议你阅读HMT协会