I’m using the Devise Ruby gem in my Ruby on Rails 3 application. When a logged in user creates one of my models, I want to save their user id as the person who created it. What should I do?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Create a migration file with a column of type
integernameduser_id, this is where the association will be stored. (see the migration guide for details on how to do this).in your model, add:
belongs_to :user(see the associations guide for more details)in the controller for your model, add
@your_model.user = current_userin the create action. This will do the association you’re looking for. (current_useris a method provided by devise that returns the User ActiveRecord for the currently logged in user)Note: there are more than one way of doing the actual association. I’m suggesting to do it in the controller but it could be done in the model or elsewhere.