【问题标题】:How to use current user in devise如何在设计中使用当前用户
【发布时间】:2019-10-12 17:09:26
【问题描述】:

我正在尝试使用 rails (6.0.0) 创建一个网站。我正在为用户注册和登录系统使用设计库。现在我的问题是“如何使用当前用户的 id 来创建帖子(帖子模型中需要 user_id)。”

这是我的app/controllers/posts_controller.rb

def create   
   @post = Post.new(post_params)   
   if @post.save   
     flash[:notice] = 'post added!'   
     redirect_to 'posts'   
   else   
     flash[:error] = 'Failed to edit post!'   
     render :new   
   end   
end   

def post_params   
   params.require(:post).permit(:name, :picture, :user_id, :description)   
end   

【问题讨论】:

    标签: ruby-on-rails devise controller


    【解决方案1】:

    使用@post = current_user.posts.new(post_params) 以便activerecord 设置正确的user_id。

    【讨论】:

      【解决方案2】:

      在设计中,您可以使用帮助器current_user 来获取登录用户。使用此帮助程序,您将访问用户(或您的模型),因此您可以使用 current_user.id 获取登录的用户 ID。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        • 2016-04-16
        • 2016-04-05
        相关资源
        最近更新 更多