【问题标题】:rails model use the instance variablerails 模型使用实例变量
【发布时间】:2012-06-29 06:56:08
【问题描述】:

我在 update 操作的 user_controller 中创建了一个实例变量 (@edit_id)。

def update
  ......
  @edit_id = 1
  ......
end

我在 user_model 中有一个 Active Record 回调

has_many :details
after_update :create_user_details
  ......
  private
  def create_user_details
     detail = user.details.build
     detail.edit_id = @edit_id
     #(this @edit_id is the user_controller update action 
     #created instance variable, but **@edit_id is nil**)
     detail.save
  end

我如何在回调动作中使用实例变量

【问题讨论】:

    标签: ruby-on-rails ruby activerecord model callback


    【解决方案1】:

    您不能在模型中使用控制器中的实例变量。
    它们都是不同对象的不同实例,因此不共享实例变量。

    你需要为你的模型提供这个值,方法是在它的实例中设置它:

    model Foo
      attr_accessor :edit_id
    
      private
      def create_user_details
       detail = user.details.build
       detail.edit_id = edit_id
       detail.save
      end
    end
    

    然后,在您的控制器中,为模型指定值并保存它。

    def update
      @foo = Foo.new
      @foo.edit_id = 1
      # Whatever other business logic you want to do
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多