Ruby on rails Rails—如何确定ID是否位于;“你有很多”;关系
我有这样的模型结构:Ruby on rails Rails—如何确定ID是否位于;“你有很多”;关系,ruby-on-rails,ruby,model,has-many,Ruby On Rails,Ruby,Model,Has Many,我有这样的模型结构: class User < ActiveRecord::Base has_many :groups end class Group < ActiveRecord::Base belongs_to :user end class用户
class User < ActiveRecord::Base
has_many :groups
end
class Group < ActiveRecord::Base
belongs_to :user
end
class用户
在我看来,我需要找出相应的用户是否在特定的组中-如何做到这一点?
是否有任何本机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.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
class收藏夹
所以我想做的基本上是:
<% if current_user.favorites.IS_THIS_GROUP_ID_IN_USERS_FAVORITES_GROUPS(@group.id)? %>
再一次对不起,我不知道我怎么会忽略了我最喜欢的型号
谢谢关于current.user.groups.include?(@group)
你也可以使用,这是在数据库中完成的
current_user.groups.exists?(@group)
有关存在的更多信息?
可以在中找到。我会选择:
current.user.groups.include?(@group)
或者,如果您只有一个id:
current.user.group_ids.include?(id)
试试看
如果您试图查看对象是否有任何组,您可能希望使用(尽管我不确定这是否是一个准确的用例):
--
包括
您可能希望尝试使用,如spickerman
所示。这将ping数组以查看其中是否存在特定元素(它不是ActiveRecord,因此必须使用id
s)