使用隐藏字段更新Rails模型而不破坏MVC

时间:2013-06-11 14:03:52

标签: model-view-controller ruby-on-rails-3.2

我在Rails 3应用程序中有一个课程模型和学生模型。课程价格更新后会影响学生中名为“余额”的属性。

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

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的一个重要原则。

我该如何正确地做到这一点?我应该在控制器中做一切吗?好像我的控制器已经变得非常大了。顺便说一下,我对此很陌生。

1 个答案:

答案 0 :(得分: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