0

我是新来的轨道。我了解控制器中的实例变量从模型中获取数据并显示到视图中。我怎样才能将实例变量发送到模型?我想对变量运行计算并将其发送回模型更新的视图。

4

1 回答 1

0

您应该将控制器实例变量作为方法参数传递给模型。这是一个例子:

# model
class MyModel < ActiveRecord::Base
  def run_computations var1, var2
    # perform complex computations
    [var1 * 2, var2 * 3]
  end
end


# controller
class MyController < ApplicationController
  def my_action
    @var1 = 10
    @var2 = 20

    @var1, @var2 = MyModel.run_computations @var1, @var2
    # MyModel.run_computations returns an array. The line above is a shortcut for
    #   picking the array apart. It is equivalent to this
    # arr = MyModel.run_computations @var1, @var2
    # @var1 = arr[0]
    # @var2 = arr[1]
  end
end
于 2012-10-21T15:50:54.007 回答