简体   繁体   English

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

[英]How to access params in the callback of a Rails model?

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. 但是params在回调方法中是未定义的。 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

params are not accessible in models, even if you pass them as a parameter then it would be consider as bad practice and might also be dangerous. params在模型中是不可访问的,即使你将它们作为参数传递,它也会被认为是不好的做法,也可能是危险的。

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

Where sign_up_date is your virtual attribute 其中sign_up_date是您的虚拟属性

params will not be available inside the models. 模型内部不提供参数。

One possible way to do this would be to define a virtual attribute in the user model and use that in the callback 一种可能的方法是在用户模型中定义虚拟属性并在回调中使用它

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

you will have to make sure that the name of the field in the form is user[:sign_up_date] 你必须确保表单中字段的名称是用户[:sign_up_date]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM