ruby-on-rails - 使用 Devise/Rails 获取当前用户的 UserID

标签 ruby-on-rails ruby devise

所以我,一个 Rails 新手,目前正在尝试从当前的 Devise session 中获取用户 ID,但我遇到了一些麻烦。

我现在在我的 Controller 中有这个:

def index
  @currentUser = current_user.id
end

我想做一个简单的 if 语句来显示/隐藏我表单中的字段。

<% if @currentUser === @product.user_id %>
          <%= link_to "Back", products_path %>
          <%= link_to "Edit", edit_product_path(@product) %>
          <%= link_to "Delete", product_path(@product), method: :delete, data: { confirm: "Are you sure?"} %>
      <% else %>
          <span></span>
<% end %>

我感觉我定义 currentUser 变量的语法有问题,但我不知道如何解决这个问题。 Stack 上有几个类似的问题,但没有一个真正适用于我或帮助我。

提前致谢!

最佳答案

我在这里看到了一些问题

def index
  @currentUser = current_user.id
end

除了@HolyMoly 已经评论过的,你应该使用下划线而不是驼峰命名法,如果这里的 current_user 为 nil,.id 将失败,导致异常.

其次,您正在通过比较 id 的值来检查“能力”,我会更改您的代码来执行此操作

<% if allow_product_delete?(@product) %>

在助手中

def allow_product_delete?(product)
  return false unless current_user
  @product.user_id == current_user.id
end

如果你正在使用设计 current_user 存在于 Controller 和 View 中,你不需要将它定义为实例变量,它已经被定义为所有操作的 Controller 方法(默认情况下)。因此,通过在您的 View 中调用 current_user,您就完成了。

如果用户未登录,current_user 将为 nil,您始终必须为此做好准备并防范它。

最后,我会研究 ability gems(cancan 或 cancancan),它们提供了一个非常好的 DSL 来处理您在这里尝试的内容。

关于ruby-on-rails - 使用 Devise/Rails 获取当前用户的 UserID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464224/

相关文章:

ruby-on-rails - RailsAdmin + Devise...身份验证

ruby-on-rails - 在设计中使用 rails secret 来加盐认证 key

ruby-on-rails - 设计登录错误不返回 JSON

ruby-on-rails - 在 ubuntu 中取消 bash 的源码

ruby-on-rails - 同时使用 MacPorts 和 RubyGems 有什么缺点吗?

ruby - 如何最好地保持作业队列清理重试/重复作业(使用 sidekiq 和 redis-semaphore)

ruby-on-rails - ActiveAdmin 和 Devise - skip_confirmation!关于创建 Action

ruby-on-rails - 表内/表行之间的 Bootstrap 折叠不起作用

ruby-on-rails - 如何使用 Ruby on Rails 随机选择要显示的内容

html - rails select_tag,如何从数组中生成带有 json 值和自定义文本的下拉列表