ruby ActiveRecord::HasManyThroughAssociationNotFoundError由于某种原因无法获取每个用户的帖子Rails

kxxlusnw  于 2022-11-04  发布在  Ruby
关注(0)|答案(2)|浏览(108)

在rails控制台中,我输入User.first.posts时,收到此错误ActiveRecord::HasManyThroughAssociationNotFoundError:无法在模型中找到关联:喜欢用户来自
用户模型

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

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

海报模型

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

结束
喜欢模型

class Like < ApplicationRecord
belongs_to :user
belongs_to :post
end

我只显示你喜欢的模型,因为它弹出的错误,但我只是想为每个用户的所有职位,所以如果我键入用户。第一。职位,所有他们的职位将显示出来

yjghlzjz

yjghlzjz1#

您需要实际定义likes关联,通过该关联定义间接关联:

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

但是,在用户和帖子之间也有两个不同的关联,它们共享相同的名称--实际上,您需要更像这样的内容:

class User < ApplicationRecord
  has_many :posts # posts that this user has created
  has_many :likes 
  has_many :liked_posts, 
     through: :likes,
     source: :post
end
r7s23pms

r7s23pms2#

您的User模型中似乎有打字错误。posts有2个关联。

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

相关问题