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

2

12

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
Rosenblum answered 28/11, 2012 at 19:25 Comment(0)
Z
8

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

Zapateado answered 28/11, 2012 at 19:42 Comment(3)
This wouldn't conflict with the database?Rosenblum
not at all unless you have an attribute of same name in database i would suggest you to have look at this rails cast railscasts.com/episodes/167-more-on-virtual-attributesZapateado
I get the following error: undefined method sign_up_date' for #<User:0x007fcd17888bc8>` when trying to assign it. Which does seem odd as without querying the database, it looks just like the name field which I have no problem assigning. Does Rails query the database upon .new or from a date_select form helper?Rosenblum
M
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]

Mirianmirielle answered 28/11, 2012 at 19:37 Comment(4)
wouldn't this try to save it to the database as well, where the sign_up_date user field doesn't exist?Rosenblum
nope, unless there is a matching column in the users table it can not save it to the databaseMirianmirielle
I get undefined method sign_up_date' for #<User:0x007fcd17888bc8>` when using date_select in my form. Or I get undefined method sign_up_date=' for #<User:0x007fcd124609d8>` if I try to do a simple assignment to it in my controller.Rosenblum
A virtual attribute shoud be 'attr_accessor' but not attr_accessible! These two things are totally different!Gahl

© 2022 - 2024 — McMap. All rights reserved.