Model view controller 在不破坏MVC的情况下使用隐藏字段更新Rails模型

Model view controller 在不破坏MVC的情况下使用隐藏字段更新Rails模型,model-view-controller,ruby-on-rails-3.2,Model View Controller,Ruby On Rails 3.2,我在Rails 3应用程序中有一个课程模型和一个学生模型。当课程价格更新时,它会影响Student中名为“balance”的属性 当我更新课程价格时,我希望通过隐藏字段传入旧价格。然后我在课程模型中有一个私有方法,看起来像这样 class Lesson < ActiveRecord::Base attr_accessible :student_id, :price belongs_to :student around_update :adjust_student_balan

我在Rails 3应用程序中有一个课程模型和一个学生模型。当课程价格更新时,它会影响Student中名为“balance”的属性

当我更新课程价格时,我希望通过隐藏字段传入旧价格。然后我在课程模型中有一个私有方法,看起来像这样

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
课程@student.balance)
结束
结束
如你所见,我试图(1)从学生余额中减去旧价格,(2)对课程进行更新,然后(3)将新价格添加到学生余额中

但是上面的代码不起作用,因为我试图从模型中访问控制器中声明的实例变量
@old_price
。经过一番探索,我意识到这不仅行不通,而且它打破了MVC的一个重要规则

我应该如何正确地做到这一点?我应该在控制器中做所有事情吗?看起来我的控制器已经变得相当大了。顺便说一句,我对这方面还不太熟悉。

请尝试以下(未经测试的)代码:

课程

它使用的是
活动模型脏
。有关此主题的更多信息,请查看。

Awesome。工作得很有魅力。不过有一个问题:您链接到的API说我必须
包括ActiveModel::Dirty
,但我没有这样做。因此,如果模型继承自
ActiveRecord::Base
,那么它会自动获取所有脏功能吗?是的。如果您使用默认的东西,您将始终可以访问Dirty。您使用的是rails。MVC已经被破坏了。
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