【问题标题】:Checking role in has-many relationship检查有很多关系中的角色
【发布时间】:2011-05-16 15:57:40
【问题描述】:

使用 Cancan,所以我需要检查用户角色。与 Users 有 has_many 关系 -> userroles(reference id's) -> roles(每个角色的名称,角色在 name 列中)。

在我的用户模型中,我有一个函数:role?(role),即role?(:admin),用于检查用户是否具有角色。

def role?(role)
   roles.include? role.to_s
end

这不行,我必须指定名称列吗?

已解决:过段时间我会把答案写下来。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    您正在将字符串与对象进行比较

    def role?(role)
      !roles.first(:conditions => {:name => role.to_s}).nil?
    end
    

    试试这个?

    基于 Dmitriy Likhten 回答的替代方案

    def role?(role)
      roles.collect{|r| r.name }.include? role.to_s
    end
    

    【讨论】:

      【解决方案2】:

      你总是可以直接过滤它...

      roles.select(&:to_s).include?(role.to_s)
      

      我的方法和 Jimmy 的方法之间的区别取决于角色是否已经在记忆中。如果是,过滤会更快,如果不是,查询会更好。

      【讨论】:

      • 您不应该使用collect 而不是select 吗? select 将只返回对象,collect 将返回一个字符串数组。您还假设角色对象上的 .to_s 方法返回其名称,它可能不会
      猜你喜欢
      • 2020-10-06
      • 2018-02-07
      • 2018-05-08
      • 2016-10-12
      • 2017-06-15
      • 2021-05-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      相关资源
      最近更新 更多