【问题标题】:Rails - how to find out if an ID is in the "has_many" relationRails - 如何找出一个ID是否在“has_many”关系中
【发布时间】:2014-07-08 23:15:14
【问题描述】:

我有这样的模型结构:

class User < ActiveRecord::Base
  has_many :groups
end
class Group < ActiveRecord::Base
  belongs_to :user
end

在视图中,我需要确定相应的用户是否在特定组中 - 怎么做? 是否有任何原生 Rails 方法可以做这样的事情:

<% if current_user.groups.IS_THIS_GROUP_ID_IN_USERS_GROUPD(@group.id)? %>

还是需要我自己写?或者,找出这一点最省时的方法是什么?

编辑: 抱歉,我犯了一个错误 - 还有一个模型,所以结构如下所示:

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end
class User < ActiveRecord::Base
  has_many :groups
end
class Group < ActiveRecord::Base
  belongs_to :user
end

所以我想要做的基本上是这样的:

<% if current_user.favorites.IS_THIS_GROUP_ID_IN_USERS_FAVORITES_GROUPS(@group.id)? %>

再次抱歉,我不知道我怎么能忽略Favorite 模型。

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby model has-many


    【解决方案1】:

    我会选择:

    current.user.groups.include?(@group)
    

    或者如果你只有一个 id:

    current.user.group_ids.include?(id)
    

    【讨论】:

      【解决方案2】:

      current.user.groups.include?(@group)怎么样

      【讨论】:

        【解决方案3】:

        您也可以使用exists?,这是在数据库中完成的。

        current_user.groups.exists?(@group)
        

        有关exists? 的更多信息,请访问Rails Active Record Querying Guide

        【讨论】:

          【解决方案4】:

          试试

          如果您想查看对象是否有任何组,您可能希望使用.try method(尽管我不确定这是否是一个准确的用例):

          current_user.try(:groups)
          

          --

          包括

          您不妨尝试使用include? method,如spickerman 所示。这将 ping 数组以查看其中是否存在特定元素(它不是 ActiveRecord,因此您必须使用 ids)

          current_user.groups.include?(@group.id) #-> true / false
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-06-11
            • 1970-01-01
            • 1970-01-01
            • 2023-03-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多