Devise认证宝石:如何保存登录的用户ID? [英] Devise authentication gem: How to save the logged in user id?

查看:64
本文介绍了Devise认证宝石:如何保存登录的用户ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby on Rails 3应用程序中使用了Devise Ruby宝石。当登录的用户创建我的一个模型时,我想保存他们的用户ID作为创建它的人。我应该怎么做?

解决方案


  1. 创建一个类型为 integer 命名为 user_id ,这是存储关联的位置。 (有关如何执行此操作的详细信息,请参阅迁移指南)。


  2. 在您的模型中,添加: belongs_to:user (请参阅关联指南了解更多详情)


  3. 对于您的模型,在创建操作中添加 @ your_model.user = current_user 。这将做你正在寻找的协会。 ( current_user 是由devise提供的一种方法,该方法为当前登录的用户返回用户ActiveRecord)


注意:有不止一种做实际关联的方式。我建议在控制器中做,但可以在模型或其他地方完成。


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.

这篇关于Devise认证宝石:如何保存登录的用户ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆