How to access parameters in a Rails model callback?

I have a callback to a model that should create a dependent object based on another field entered into the form. But params is undefined in the callback method. Is there any other way to access it? What is the correct way to pass parameters to a callback method 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 
+8
ruby-on-rails activerecord ruby-on-rails-3 activemodel
source share
3 answers
Options

not available in models, even if you pass them as a parameter, then this will be considered bad practice and can also be dangerous.

What you can do is create a 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

+6
source share

What you need to do is move this code to the controller, params not available on models.

 if @user.save enrollments.create!(status: 'signed up', started: params[:sign_up_date]) end 
+1
source share
Options

will not be available inside models.

One possible way to do this is to define a virtual attribute in the user model and use it 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 need to make sure that the field name on the form is user [: sign_up_date]

+1
source share

All Articles