Categories
Rails

Rails and devise: building associations at record creation time

In your “create” method, on your controller:

@search = current_user.searches.build(params[:search])

Assumes:

  • current_user contains your user record (via devise)
  • search, searches is the model of the record you are trying to create
  • build is just there to marshal your posted form parameters, so no need to include them (RoR is magical like that)
  • current_user.searches is building the relationship between those two, so the search you are creating will have the associated user_id on it

So your User model:

has_many :searches, dependent: :destroy

And your Searches model:

belongs_to :user

This is the very basic association operation. For more details and the list of all possible combinations you can form (from the source):

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *