Rails-检查has_many关联中是否存在记录 [英] Rails - check if record exists in has_many association

查看:78
本文介绍了Rails-检查has_many关联中是否存在记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我的问题的措词是否正确。

I'm not sure if my question is worded correctly.

我有三种模型: User Item UserItem

I have three models: User, Item, and 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具有枚举状态:[:待批准,已批准] 。因此,我需要查看 current_user 是否具有某个:pending 项。

I need a way to see if a user has an item to make if statements in my item views But here's the catch, user_items have enum status: [ :pending, approved]. So I need to see if a current_user has a certain :pending item.

例如,当用户访问item1的视图页面时,我让item_controller的show动作声明 @item = Item.find_by_id(params [:id])。但是然后我可以用这个 @item 做什么,看看用户是否有这个物品?

For example when a user visits item1's view page I have the item_controller's show action declare @item = Item.find_by_id(params[:id]). But then what can I do with this @item to see if a user has this item?

推荐答案

尝试:

current_user.items.exists?(params[:id])

current_user.items.exists?(@item.id)

这篇关于Rails-检查has_many关联中是否存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆