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

纵饮孤独 提交于 2019-12-04 19:02:50

问题


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

回答1:


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.

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




回答2:


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]



来源:https://stackoverflow.com/questions/13612846/how-to-access-params-in-the-callback-of-a-rails-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!