多对多关系ActiveRecord :: HasManyThroughAssociationNotFoundError

时间:2018-01-17 15:22:18

标签: ruby-on-rails ruby activerecord

您好我正在尝试在我的应用中建立多对多的关系。我有两个模型Count.rb

class Count < ApplicationRecord
  has_many :users, through: :counts_users
end

users.rb

class User < ApplicationRecord
  has_many :counts, through: :counts_users
end

counts_users.rb

class CountsUser < ApplicationRecord
  belongs_to :user
  belongs_to :count
end

现在我可以创建一个计数

Count.new(message: 'hello')

但如果我那么做

Count.last.users << User.last

我收到错误ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :counts_users in model ErrorCount

我认为我在设置关联方面做错了,但我不确定是什么?

1 个答案:

答案 0 :(得分:0)

您的模型关联应该像这样设置:

# count.rb
class Count < ApplicationRecord
  has_many :counts_users
  has_many :users, through: :counts_users
end

# user.rb
class User < ApplicationRecord
  has_many :counts_users
  has_many :counts, through: :counts_users
end

# counts_user.rb
class CountsUser < ApplicationRecord
  belongs_to :user
  belongs_to :count
end

请参阅:the Rails Guides on has_many :through Association