Rails - check if record exists in has_many association

后端 未结 4 1872
滥情空心
滥情空心 2021-01-01 13:33

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

I have three models: User, Item, and UserItem.

user has_many         


        
4条回答
  •  醉话见心
    2021-01-01 14:29

    1) Add a scope to User_item class

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

    2) Use that scope in an instance method of Item class:

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

    Then you can use

    if @item.is_pending_with_someone? 
      ...
    

提交回复
热议问题