Rails - 检查 has_many 关联中是否存在记录

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)