gpt4 book ai didi

ruby-on-rails - 如何将Devise的current_user传递为user_id?

转载 作者:行者123 更新时间:2023-12-04 04:07:18 25 4
gpt4 key购买 nike

我正在通过创建一个简单的应用程序来练习Ruby on Rails,用户可以在其中注册(使用Devise)并发布文章。

安装Devise之后,我继续为这些文章生成一个脚手架

 rails g scaffold article title:string article:text user_id:integer

然后创建Devise用户 Controller
rails generate devise User

我的文章 Controller :
class Article < ActiveRecord::Base
belongs_to :user
end

我的用户 Controller :
class User < ActiveRecord::Base
has_many :articles

devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

attr_accessible :email, :password, :password_confirmation, :remember_me
end

现在我的问题是:如何做到这一点,以便 http://localhost:3000/articles/new/中的user_id自动成为current_user.id?

同样,在 http://localhost:3000/articles/中,用户只能查看与其user_id相关联的文章,而不能查看其他任何人。为此,我应该对商品 Controller 进行哪些更改?

这是我第一次在此处发布Stack Overflow,感谢您的帮助。

编辑找到了第一个问题的解决方案,以供将来引用。

我放
<%= f.hidden_field :user_id %> 

在_form.html.erb中,以及
def create
@article.user_id = current_user.id
...
end

给我的文章管理员。这成功地将current_user.id完美地传递为文章的user_id。

最佳答案

Now my question is: how do you make it so that user_id in http://localhost:3000/articles/new/ is automatically current_user.id?



您应该将这一行添加到articles_controller的“def new”中
@ ask.user_id = current_user.id

所以 form_for @ask要求 user_id@ask属性并显示它。但我不建议在实际应用中执行此操作,在该应用中,您可能会在“articles_controller”的“def create”中处理此步骤

`Also, in http://localhost:3000/articles/ the user should only be able to view the articles associated with their user_id, not anyone elses. What changes to the articles controller should I make to do this?



articles_controllerdef index中,更改为 @articles = Article.where(user_id:current_user.id)。请注意,您还应该添加 before_filter :require_user以确保 current_user不为nil。

关于ruby-on-rails - 如何将Devise的current_user传递为user_id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8472370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com