Rails - check if record exists in has_many association

℡╲_俬逩灬. 提交于 2019-11-30 11:31:48
lei liu

Try:

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

Or

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

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

Extending @lei-liu's answer here. One can find if the record exists among the many or not, through: current_user.items.exists?(params[:id])

At the same time, exists? allows one to filter through the columns besides id, and also allows for more complicated conditions, like the following:

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

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? 
  ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!