0

Hi I'm trying to set up a many to many relationship in my app. I have two models Count.rb

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

users.rb:

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

and counts_users.rb:

class CountsUser < ApplicationRecord
  belongs_to :user
  belongs_to :count
end

Now I can create a count

Count.new(message: 'hello')

but if I then do

Count.last.users << User.last

I get the error ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :counts_users in model ErrorCount

I assume I've done something wrong setting up the association, but I'm not sure what?

user2320239
  • 1,021
  • 2
  • 18
  • 43
  • 1
    https://stackoverflow.com/questions/1781202/could-not-find-the-association-problem-in-rails should point you in the right direction – Mark Jan 17 '18 at 15:27

1 Answers1

0

Your models' associations should be set up like this:

# 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

See: the Rails Guides on has_many :through Association

amrrbakry
  • 589
  • 7
  • 17