2016-06-18 2 views
0

私はRails 5を使用しており、this redirect_back methodを使用しようとしています。リダイレクトメソッド呼び出しでヘルパーメソッドを使用できますか?

しかし、私の問題は、質問& Answerオブジェクトの両方で呼び出すことができるComment#Createに使用していることです。だからそれに応じて、私はそれがそれぞれのオブジェクト(もちろん、2つの異なるルーティングパスを持つ)にリダイレクトしたい。

私が行ったことは、カスタムメソッドを追加して、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... 
...       

redirect_back Railsのコード:

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

パーフェクト。これが私の必要なものです。目の第2セット。ありがとう! – marcamillion

関連する問題