如何在rails动作中传入两个不同的变量id?

时间:2016-03-16 05:39:20

标签: ruby-on-rails

这是我的评论控制器;评论属于主题和帖子,主题和帖子有很多评论。

class CommentsController < ApplicationController

  before_action :require_sign_in

  before_action :authorize_user, only: [:destroy]

...
...
  def destroy

    @topic = Topic.find(params[:topic_id])
    topic_comment = @topic.comments.find(params[:id])

    @post = Post.find(params[:post_id])
    post_comment = @post.comments.find(params[:id])

    if post_comment.destroy
      flash[:notice] = "Comment was deleted"
      redirect_to [@post.topic, @post]
    elsif topic_comment.destroy
      flash[:notice] = "Comment was deleted"
      redirect_to @topic
    else
      flash[:alert] = "Comment counld't be deleted. Try again"
      redirect_to [@post.topic, @post]
    end

  end

  private


  def comment_params
    params.require(:comment).permit(:body)
  end

  def authorize_user
    comment = Comment.find(params[:id])

    unless current_user == comment.user || current_user.admin?
      flash[:alert] = "You do not have permission to delete a comment."
      redirect_to [comment.post.topic, comment.post]
    end
  end

end

我的路线构建正确,post.comments(种子)和topic.com(种子)在我的应用程序中正确显示。当我仅通过destroy时,上述操作@post有效。但是,我在介绍@topic时收到错误。如果我通过topic点击我的删除按钮,我会在浏览器中收到:(无法找到没有ID的帖子)。或者,我在post.comment上点击删除时收到此错误(在引入@topic之前有效):( 无法找到带有'id'= 的主题)

我应该在destroy动作中创建某种类型的循环,在类中创建一个方法,还是在模块中创建另一个循环?我在看这个错误,应该尝试另一个想法吗?我基本上想要在点击时销毁我的topic.com,并点击了我的post.com。

由于

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

class CommentsController < ApplicationController
  before_action :require_sign_in
  before_action :authorize_user, only: [:destroy]

  def destroy
    @commentable = find_commentable
    @comment = @commentable.comments.find(params[:id])

    if @comment.destroy
      flash[:notice] = "Comment was deleted"
      redirect_to [@commentable.topic, @commentable]  
    else
      flash[:alert] = "Comment counld't be deleted. Try again"
      redirect_to [@commentable.topic, @commentable]  
    end
  end  

  private
  def find_commentable
    if params[:topic_id].present?
      Topic.find(params[:topic_id])
    elsif params[:post_id].present?
      Post.find(params[:post_id])
    end
  end 

  def comment_params
    params.require(:comment).permit(:body)
  end

  def authorize_user
    comment = Comment.find(params[:id])

    unless current_user == comment.user || current_user.admin?
      flash[:alert] = "You do not have permission to delete a comment."
      redirect_to [comment.post.topic, comment.post]
    end
  end
end

答案 1 :(得分:0)

尝试以下代码

   @topic = Topic.find_by_id(params[:topic_id]) ##it will not raise an error if params[:topic_id] not present, returns either nil or object
   topic_comment = @topic.comments.find(params[:id]) if @topic.present?

    @post = Post.find_by_id(params[:post_id]) ##it will not raise an error if params[:post_id] not present, returns either nil or object
    post_comment = @post.comments.find(params[:id]) if @topic.present?

##rest of your logic.