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

时间:2017-04-13 13:20:42

标签: ruby-on-rails polymorphic-associations

我设置了一些多态关系,并且主要用途很好。这是为了让用户能够评论文章和咖啡店。

但是,我很难在其个人资料页面上显示用户评论列表。在未来,我还希望用户能够“喜欢”和“想要去”不同的咖啡店,我也想在他们的个人资料页面上显示。我希望一旦我得到显示当前评论的逻辑,其余的将是轻而易举的;)

所以我拥有:

模型

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

我收到了未定义评论的错误。

1 个答案:

答案 0 :(得分:2)

ok首先返回这个以显示将其移动到索引是不是解决了索引未被调用的问题所以写这样的显示。

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)%>