我在Rails 3应用程序中有一个课程模型和一个学生模型。当课程价格更新时,它会影响到Student中一个名为“balance.‘”的属性。
当我更新课程价格时,我希望通过隐藏字段传递旧价格。然后我在Lesson Model中有一个私有方法,如下所示。
class Lesson < ActiveRecord::Base
attr_accessible :student_id, :price
belongs_to :student
around_update :adjust_student_balance
private
def adjust_student_balance
@student = Student.find(self.student_id)
@student.balance -= @old_price
yield
@student.balance += self.price
@student.update_attributes(:balance => @student.balance)
end
end如你所见,我正在尝试(1)从学生的余额中减去旧价格,(2)对课程执行更新,然后(3)将新价格添加到学生的余额中。
但是上面的代码不起作用,因为我试图从模型访问在控制器中声明的实例变量@old_price。经过一番搜索,我意识到这不仅行不通,而且还破坏了MVC的一个重要原则。
我应该如何正确地做这件事?我应该在控制器中做所有的事情吗?看起来我的控制器已经变得相当大了。顺便说一句,我在这方面是个新手。
发布于 2013-06-13 03:58:28
尝试以下(未测试的)代码:
class Lesson < ActiveRecord::Base
attr_accessible :student_id, :price
belongs_to :student
after_save :adjust_student_balance
private
def adjust_student_balance
student = self.student
student.balance -= self.price_was
student.balance += self.price
student.save
end
end它使用Active Model Dirty。有关此主题的更多信息,请查看http://api.rubyonrails.org/classes/ActiveModel/Dirty.html。
https://stackoverflow.com/questions/17046104
复制相似问题