ActiveRecord_Associationundefined方法"评论"#<帖子::ActiveRecord_Associations_CollectionProxy:>s_Coll



我的应用程序中有 3 个模型,即 - 用户、帖子和评论。他们像这样关联

  • 用户可以拥有帖子
  • 帖子属于用户
  • 一个帖子可以有很多评论
  • 评论属于用户

帖子模型

class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
validates :title, presence: true
validates :body, presence: true
end

用户模型

class User < ApplicationRecord
before_create { generate_token(:auth_token) }
before_save { self.email = email.downcase }
has_secure_password
has_many :posts

validates :name, presence: true
validates :email, presence: true, uniqueness: true
validates :password, confirmation: true
validates :password_confirmation, presence: true, unless: Proc.new { |a| !a.new_record? && a.password.blank? }
def send_password_reset
generate_token(:reset_password_token)
self.reset_password_sent_at = Time.zone.now
save!
UserMailer.password_reset(self).deliver
end

def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
end

审查模型

class Review < ApplicationRecord
belongs_to :user
end

用户控制器 - 显示方法

def show
@user = User.find(params[:id])
@posts = @user.posts
@reviews = @posts.reviews //This line shows error
end

我认为我关联这些模型的方式有问题。 我想显示对该帖子的评论。我从帖子用户控制器显示....但是当我尝试以相同的方式显示评论时,我。我

我手动去并在rails控制台上发表了评论。

从架构查看表

create_table "reviews", force: :cascade do |t|
t.string "comment"
t.string "user_id"
t.string "post_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end

可以在代码中看到两个问题。

1 - 您尚未在审核模型中定义帖子和审核之间的关系。

class Review < ApplicationRecord
belongs_to :user
belongs_to :post
end

2 - 您正在尝试从帖子关系中获取评论。如果您想获得给定用户的所有评论。您可能应该需要

def show
@user = User.find(params[:id])
@posts = @user.posts
@reviews = @user.reviews
end

或者,您可能必须通过以下方式为视图中的每篇文章加载评论

post.reviews

最新更新