0

User.rbQuestion.rbおよびAnswer.rbモデルを使用したRailsアプリケーションがあります。これらの各モデル間には、予測可能な関係が定義されています。ユーザーがhas_many質問し、ユーザーhas_manyが回答します。質問has_manyも答えます。

質問者に「 」として回答を選択するオプションを提供しようとしていますbest answer。そのため、Answers コントローラーに「bestAnswer」コントローラー アクションを作成しました。このコントローラー アクションでは、ベスト アンサーの ID を に保存し、特定のアンサーがベスト アンサーとして選択され@questionたことも示します。@answerしたがって、私は とupdate_attributesの両方を同時に@questionしよ@answerうとしました

if @question.update_attributes(:accepted_answer_id => @answer.id) && @answer.update_attributes(:accepted => true)

フルメソッド。

 def bestanswer


    @answer = Answer.find(params[:answer_id])
    @question = Question.find(params[:question_id])     
         if @question.update_attributes(:accepted_answer_id => @answer.id) && @answer.update_attributes(:accepted => true)
             redirect_to @question, notice: 'You have accepted as best answer' 
         else
             redirect_to @question, notice: 'There was a problem marking this as best answer. Please try again.' 
         end
 end 

これは機能しますが、Rails がトランザクションをサポートしていることも認識しています。経験が浅いので、上記の方法で物事を行うべきか、それともトランザクションを行うべきか、または何か他のことを行うべきかわかりません。私が取引をするべきだと思うなら、どのように書きますか? トランザクションはモデルで実行する必要があると思いますが、モデルなどでインスタンス変数を使用することや、どのモデルに書き込むかがわからないため、少し混乱しています。

アップデート。最初の回答の提案を次の方法で実装しました。動作しますが、私には奇妙に見えます。OP がトランザクションの書き方を尋ねたので、誰かがトランザクションをコントローラ アクションに統合する方法を明確にしてくれることを期待していました。

            if ActiveRecord::Base.transaction do
                      @question.update_attributes! :accepted_answer_id => @answer.id
                      @answer.update_attributes! :accepted => true
                    end
                 redirect_to @question, notice: 'You have accepted as best answer' 
             else
                 redirect_to @question, notice: 'There was a problem marking this as best answer. Please try again.' 
             end
4

1 に答える 1

1

できるよ

ActiveRecord::Base.transaction do
  @question.update_attributes! :accepted_answer_id => @answer.id
  @answer.update_attributes! :accepted => true
end

ここで使用するのは!、ActiveRecord が例外が発生した場合にのみトランザクションをロールバックし、何か問題が発生した場合に の!バージョンがトリガーされるためです。update_attributes

また、has_one :accepted_answer質問モデルに関係が設定されている場合は、使用する必要があります

@question.update_attributes! :accepted_answer => @answer

ID を手動で設定する代わりに。一般的には、ActiveRecord に ID を管理させた方がよいでしょう。

于 2013-03-25T04:18:33.567 に答える