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

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

问题描述

我不确定我的问题是否措辞正确.

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

我有三个模型:UserItemUserItem.

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 具有 enum 状态:[:pending,approved].所以我需要看看 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 的显示操作声明 @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天全站免登陆