Home > Software design >  ActiveRecord::HasManyThroughAssociationNotFoundError cannot get the posts for each user for some rea
ActiveRecord::HasManyThroughAssociationNotFoundError cannot get the posts for each user for some rea

Time:10-01

In the rails console I am inputing User.first.posts and i am getting this error ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :likes in model User from

USER MODEL

class User < ApplicationRecord
    has_secure_password
    has_many :posts
    has_many :comments
    has_many :posts, through: :likes

    validates :name, presence: true, uniqueness: true
end

POSTS MODEL

class Post < ApplicationRecord
belongs_to :user
has_many :comments
has_many :likes
has_many :users, through: :likes
def number_of_comments
    comments.length
end
def number_of_likes
    likes.length
end

end

LIKES MODEL

class Like < ApplicationRecord
belongs_to :user
belongs_to :post
end

Im only showing you the likes model because its popping up in the error but i just want all the posts for each user so if i type User.first.posts all their posts will show up

CodePudding user response:

You need to actually define the likes assocation that you're defining the indirect assocation through:

class User < ApplicationRecord
  # ...
  has_many :likes # this was missing
  has_many :posts, through: :likes
end

CodePudding user response:

There's seems to be a typo in your User model. There are 2 associations for posts.

class User < ApplicationRecord
    has_secure_password
    has_many :posts
    has_many :comments
    # has_many :posts, through: :likes # <-- this i think is the culprit.
    # it should be like this:
    has_many :likes, through: :posts

    validates :name, presence: true, uniqueness: true
end
  • Related