如何在Rails模型的回调中访问参数?

问题描述:

我有一个模型的回调,该模型需要根据表单中输入的另一个字段创建一个依赖对象。但是 params 在回调方法中未定义。还有另一种访问方式吗?从表单传递回调方法参数的正确方法是什么?

I have a callback of a model that needs to create a dependent object based on another field entered in the form. But params is undefined in the callback method. Is there another way to access it? What's the proper way to pass a callback method parameters from a form?

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :enrollments

  after_create :create_enrollment_log
  private
  def create_enrollment_log
    enrollments.create!(status: 'signed up', started: params[:sign_up_date])
  end
end


在模型中无法访问参数,即使您将它们作为参数传递,也将被视为不正确的做法,并且也很危险。

您可以做的就是创建虚拟属性并将其在模型中使用。

What you can do is to create virtual attribute and use it in your model.

class User < ActiveRecord::Base
 attr_accessible :name, :sign_up_date
 has_many :enrollments

 after_create :create_enrollment_log
 private
 def create_enrollment_log
   enrollments.create!(status: 'signed up', started: sign_up_date)
 end
end

其中sign_up_date是您的虚拟属性

Where sign_up_date is your virtual attribute