Rails - 检查 has_many 关联中是否存在记录
Rails - check if record exists in has_many association
我不确定我的问题是否措辞正确。
我有三个模型:User
、Item
和 UserItem
。
user has_many :user_items
user has_many :items, through :user_items
item has_many :user_items
item has_many :users -> {uniq}, through :user_items
item belongs_to :user
user_item belongs_to :user
user_item belongs_to :item
我需要一种方法来查看用户是否有一个项目可以在我的项目视图中做出 if
声明但问题是,user_items 有 enum status: [ :pending, approved]
。所以我需要看看 current_user
是否有某个 :pending
项目。
例如,当用户访问 item1 的视图页面时,我有 item_controller 的显示操作声明 @item = Item.find_by_id(params[:id])
。但是我可以用这个 @item
做什么来查看用户是否有这个项目?
尝试:
current_user.items.exists?(params[:id])
或
current_user.items.exists?(@item.id)
But then what can I do with this @item to see if a user has this item?
我认为您在这里缺少的是模型方法。例如,如果您向 Item 模型添加了一个名为 belongs_to_user_in_pending_state 的方法,您就可以在需要的任何地方调用 @item.belongs_to_user_in_pending_state(current_user)
。
def belongs_to_user_in_pending_state(user)
if self.user_items.pending.select {|s| s.user == user}.count > 0
return true
else
return false
end
end
1) 添加作用域 User_item class
scope :pending, -> {where status: 'pending'}
2) 在 Item class:
的实例方法中使用该作用域
def is_pending_with_someone?
self.user_items.pending.count > 0
end
然后你可以使用
if @item.is_pending_with_someone?
...
在这里扩展@lei-liu的回答。可以通过:current_user.items.exists?(params[:id])
查询记录是否存在于众多之中
同时,exists?
允许过滤除id
之外的列,也允许更复杂的条件,如下所示:
current_user.items.exists?('id > 3')
current_user.items.exists?(name: 'some_name')
我不确定我的问题是否措辞正确。
我有三个模型:User
、Item
和 UserItem
。
user has_many :user_items
user has_many :items, through :user_items
item has_many :user_items
item has_many :users -> {uniq}, through :user_items
item belongs_to :user
user_item belongs_to :user
user_item belongs_to :item
我需要一种方法来查看用户是否有一个项目可以在我的项目视图中做出 if
声明但问题是,user_items 有 enum status: [ :pending, approved]
。所以我需要看看 current_user
是否有某个 :pending
项目。
例如,当用户访问 item1 的视图页面时,我有 item_controller 的显示操作声明 @item = Item.find_by_id(params[:id])
。但是我可以用这个 @item
做什么来查看用户是否有这个项目?
尝试:
current_user.items.exists?(params[:id])
或
current_user.items.exists?(@item.id)
But then what can I do with this @item to see if a user has this item?
我认为您在这里缺少的是模型方法。例如,如果您向 Item 模型添加了一个名为 belongs_to_user_in_pending_state 的方法,您就可以在需要的任何地方调用 @item.belongs_to_user_in_pending_state(current_user)
。
def belongs_to_user_in_pending_state(user)
if self.user_items.pending.select {|s| s.user == user}.count > 0
return true
else
return false
end
end
1) 添加作用域 User_item class
scope :pending, -> {where status: 'pending'}
2) 在 Item class:
的实例方法中使用该作用域def is_pending_with_someone?
self.user_items.pending.count > 0
end
然后你可以使用
if @item.is_pending_with_someone?
...
在这里扩展@lei-liu的回答。可以通过:current_user.items.exists?(params[:id])
同时,exists?
允许过滤除id
之外的列,也允许更复杂的条件,如下所示:
current_user.items.exists?('id > 3')
current_user.items.exists?(name: 'some_name')