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

时间:2016-06-18 01:10:39

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

我正在使用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

1 个答案:

答案 0 :(得分:1)

我也没有马上注意到,但你的行语法无效:

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.') }