Rails - check if record exists in has_many association

user4584963 picture user4584963 · Apr 8, 2016 · Viewed 19.8k times · Source

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

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

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.

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?

Answer

lei liu picture lei liu · Apr 8, 2016

Try:

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

Or

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