Rails - check if record exists in has_many association

后端 未结 4 1876
滥情空心
滥情空心 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:09

    But then what can I do with this @item to see if a user has this item?

    I think what you are missing here is model methods. For example, if you added a method to the Item model called belongs_to_user_in_pending_state, you'd be able to call @item.belongs_to_user_in_pending_state(current_user) anywhere you need it.

    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
    

提交回复
热议问题