我有一个User.rb
,Question.rb
和Answer.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
谢谢,但你能提供一些信息。我是否将该交易直接放在bestanswer行动中?如果是这样,我如何编写重定向以成功保存或保存失败?另外,我喜欢has_one这个想法:accepted_answer,但是我需要在Answer模型中添加更多内容以使其工作吗?我已经在答案模型上做了belongs_to:问题。谢谢,如果你能帮助。我有点缺乏经验,所以你可以提供的任何细节将不胜感激。 – BrainLikeADullPencil 2013-03-25 04:36:50
我得到的交易在OP的更新中显示,但它看起来很奇怪,我已经实现了它。那是你怎么做的?我真的只能通过看到其他人的代码来学习,而且我从来没有见过其中之一使用过...... – BrainLikeADullPencil 2013-03-26 05:58:09
我不确定Rails会从事务中返回“false”。如果是这样,那么我可能会将结果存储在一个变量中,然后使用'if',而不是在整个事务方法中使用'if'。你也可以从'ActiveRecord :: Rollback'中解救出来,每当触发回滚时就会抛出。所以如果你发现异常,你可以运行if语句的else部分,否则返回成功。 – 2013-03-26 13:29:10