开发者

Devise authentication gem: How to save the logged in user id?

开发者 https://www.devze.com 2023-01-17 06:15 出处:网络
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'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?


  1. Create a migration file with a column of type integer named user_id, this is where the association will be stored. (see the migration guide for details on how to do this).

  2. in your model, add: belongs_to :user (see the associations guide for more details)

  3. in the controller for your model, add @your_model.user = current_user in the create action. This will do the association you're looking for. (current_user is 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号