我在Rails 3应用程序中有一个Lesson Model和一个学生模型。当课程价格更新时,它会影响学生中称为“余额”的属性。使用隐藏字段更新Rails模型而不打破MVC
当我更新课程价格时,我想通过隐藏字段以旧价格传递。然后我得到了在示范课看起来像这样的私有方法..
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的一个重要规则。
我应该如何正确地做到这一点?我应该在控制器中做所有事情吗?看来我的控制器已经变得相当大了。顺便说一下,我对此很新。
您正在使用导轨。 MVC已经被打破。 –