Rails - check if an entry exists in the has_many association

I am not sure if my question is formulated correctly.

I have three models: User, Itemand 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 to find out if the user has an element for creating statements ifin the views of my positions. But here catch, user_items have enum status: [ :pending, approved]. So I need to see if there is an current_userelement :pending.

For example, when a user visits the page view1 item1, I have the action show_controller show declare @item = Item.find_by_id(params[:id]). But what can I do with this @itemto find out if the user has this element?

+14
4

Try:

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

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

@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
0

@lei-liu . , , : current_user.items.exists?(params[:id])

exists? id, , :

current_user.items.exists?('id > 3')
current_user.items.exists?(name: 'some_name')
0

1) User_item

scope :pending, -> {where status: 'pending'}

2) Item:

def is_pending_with_someone?
  self.user_items.pending.count > 0
end

if @item.is_pending_with_someone? 
  ...
-1

All Articles