从 rails 中的多态表中检索数据

Retrieving data from polymorphic tables in rails

我设置了一些多态关系,并且可以很好地满足主要目的。这是为了让用户能够对文章和咖啡店发表评论。

但是,我很难在用户的个人资料页面上显示用户的评论列表。将来我还希望用户能够 'favourite' 和 'want to go to' 不同的咖啡店,我也想在他们的个人资料页面上显示这些咖啡店。我希望一旦我掌握了显示当前评论的逻辑,剩下的就轻而易举了 ;)

所以我有:

型号

class User < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :commentable, polymorphic: true

end

class Coffeeshop < ApplicationRecord
  has_many :comments, as: :commentable
end

class Article < ApplicationRecord
  has_many :comments, as: :commentable

end

评论控制器

class CommentsController < ApplicationController
  before_action :load_commentable
  before_action :authenticate_user!
  before_action :comment_auth, only:  [:edit, :update, :destroy]

  def index
    @comments = @commentable.comments
  end

  def new
    @comment = @commentable.comments.new
  end

  def create
    @comment = @commentable.comments.new(allowed_params)
    @comment.user_id=current_user.id if current_user
    if @comment.save
      redirect_to @commentable, notice: "Comment created."
    else
      render :new
    end

  end

  def update
    @comment = Comment.find(params[:id])
    if @comment.update(comment_params)
      redirect_to @commentable
    else
      render 'edit'
    end
  end

  def destroy
    @comment = Comment.find(params[:id])
    @commentable = @comment.commentable
    if @comment.destroy
      flash[:success] = "Comment Destroyed!"
      redirect_to :back
    end

    end

  private

  def allowed_params
  params.require(:comment).permit(:name, :body)
end

  def load_commentable
    resource, id = request.path.split('/')[1,2]
    @commentable = resource.singularize.classify.constantize.find(id)
  end


  def comment_params
     params.require(:comment).permit(:body).merge(user_id: current_user.id)
  end

配置文件控制器

class ProfileController < ApplicationController
before_action :authenticate_user!

  def index

  end

  def show
    @user = User.find.current_user(params[:id])
    @comments = @commentable.comments

  end

在views/profile/show.html.erb。我正在尝试做:

<h3>Your Latest Comment</h3>
<%=@comment.user.body%>

但这显然是不正确的,因为我得到 Couldn't find User without an ID。来自 ProfileController#show

更新

如果我将 ProfileController 更改为

before_action :authenticate_user!

  def index
    @user = User.find.current_user(params[:user_id])
  end

  def show
    @comments = @commentable.comments
  end

我收到未定义注释的错误。

首先确定 return 这表明将它移动到索引并没有解决索引未被调用的问题,所以这样写 show。

def show
 @user = current_user #you get instance of a user that is logged in
 @comments =  @user.comments
end

我不知道你的评论迁移中是否有user_id,但如果没有,你必须写

class User < ApplicationRecord
  has_many :comments, as: :commentable
end

查看

<h3>Your Latest Comment</h3>
<%=@comments.try(&:last).try(&:body)%>