2013-06-11 28 views
0

我在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的一个重要规则。

我应该如何正确地做到这一点?我应该在控制器中做所有事情吗?看来我的控制器已经变得相当大了。顺便说一下,我对此很新。

+0

您正在使用导轨。 MVC已经被打破。 –

回答

0

试试下面的(未经测试)代码:

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

+0

太棒了。像魅力一样工作。但有一个问题:你链接到的API说我必须包含ActiveModel :: Dirty',但我没有这样做。所以如果模型继承自'ActiveRecord :: Base',那么它会自动获得所有的脏功能? – niftygrifty

+0

是的。如果你使用默认的东西,你总是可以访问脏。 – wintermeyer