【问题标题】:ActiveRecord_Associationundefined method `reviews' for #<Post::ActiveRecord_Associations_CollectionProxy:>s_CollectionProxy#<Post::ActiveRecord_Associations_CollectionProxy:>s_CollectionProxy 的 ActiveRecord_Associationundefined 方法“评论”
【发布时间】:2019-12-01 09:07:30
【问题描述】:

我的应用程序中有 3 个模型,即用户、帖子和 cmets。它们是这样关联的

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

帖子模型

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

我认为我关联这些模型的方式有问题。 我想显示在该帖子上发布的 cmets。我从帖子用户控制器中显示....但是当我尝试以相同的方式显示 cmets 时。我

我已手动离开并发表评论以在 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

【问题讨论】:

    标签: ruby-on-rails-5 ruby-on-rails-5.2 ruby-on-rails-6


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      • 2022-01-02
      • 2011-09-09
      • 2011-11-21
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多