User.rb
、 Question.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