我可以在重定向方法调用中使用辅助方法吗?

Can I use a helper method in a redirect method call?

我正在使用 Rails 5,我正在尝试使用 this redirect_back method

但是,我的问题是我将它用于 Comment#Create,它可以为问答对象调用。因此,根据它的不同,我希望它重定向回相应的对象(当然有两个不同的路由路径)。

所以,我所做的是创建一个问题,添加一个自定义方法,然后尝试在 redirect_back 调用中调用该方法,但它似乎不起作用。

关注是这样的:

module CommentRedirect
  extend ActiveSupport::Concern

def question_or_answer(comment)
  if comment.commentable_type.eql? "Question"
    question_path(comment.commentable)
  elsif comment.commentable_type.eql "Answer"
    question_path(comment.commentable.question)
  end
end

end

然后我的 Comment#Create 看起来像这样:

format.html { redirect_back(fallback_location: question_or_answer(@comment)), notice: 'Comment was successfully created.' }

我得到的错误是这样的:

SyntaxError at /comments
syntax error, unexpected ',', expecting '}'
... question_or_answer(@comment)), notice: 'Comment was success...
...                        

鉴于这是 Rails 中的 redirect_back 代码:

def redirect_back(fallback_location:, **args)
  if referer = request.headers["Referer"]
    redirect_to referer, **args
  else
    redirect_to fallback_location, **args
  end
end

我可以按照我尝试的方式使用辅助方法吗?

如果没有,我还能如何实现我想做的事情?

编辑 1

这是整个 Comment#Create 方法:

  def create
    @comment = Comment.new(comment_params)
    @comment.user = current_user

    respond_to do |format|
      if @comment.save
        format.html { redirect_back(fallback_location: question_or_answer(@comment)), notice: 'Comment was successfully created.' }
        format.json { render :show, status: :created, location: @comment }
      else
        format.html { render :new }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

我也没有立即注意到,但是你的行是无效的语法:

format.html { redirect_back(fallback_location: question_or_answer(@comment)), notice: 'Comment was successfully created.' }

应该是这样的:

format.html { redirect_back(fallback_location: question_or_answer(@comment), notice: 'Comment was successfully created.') }