2013-03-25 71 views
0

我有一個User.rbQuestion.rbAnswer.rb模型的Rails應用程序。可預測的關係定義在每個這些模型之間。用戶has_many的問題,用戶也是has_many的回答。 has_many也有問題。更新兩個實例變量在同一時間

我想給問題提問者選擇一個答案爲'best answer'。因此,我在Answers控制器中創建了「bestAnswer」控制器操作。在此控制器操作中,我希望將@question中的最佳答案存儲在ID中,並且還指出特定的@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 

回答

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。

+0

謝謝,但你能提供一些信息。我是否將該交易直接放在bestanswer行動中?如果是這樣,我如何編寫重定向以成功保存或保存失敗?另外,我喜歡has_one這個想法:accepted_answer,但是我需要在Answer模型中添加更多內容以使其工作嗎?我已經在答案模型上做了belongs_to:問題。謝謝,如果你能幫助。我有點缺乏經驗,所以你可以提供的任何細節將不勝感激。 – BrainLikeADullPencil 2013-03-25 04:36:50

+0

我得到的交易在OP的更新中顯示,但它看起來很奇怪,我已經實現了它。那是你怎麼做的?我真的只能通過看到其他人的代碼來學習,而且我從來沒有見過其中之一使用過...... – BrainLikeADullPencil 2013-03-26 05:58:09

+0

我不確定Rails會從事務中返回「false」。如果是這樣,那麼我可能會將結果存儲在一個變量中,然後使用'if',而不是在整個事務方法中使用'if'。你也可以從'ActiveRecord :: Rollback'中解救出來,每當觸發回滾時就會拋出。所以如果你發現異常,你可以運行if語句的else部分,否則返回成功。 – 2013-03-26 13:29:10

相關問題