Rails - check if record exists in has_many association

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

    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')
    

提交回复
热议问题