Search code examples
ruby-on-railsruby-on-rails-4cancan

Rails, cancan - making an empty where query false


I'm using cancan, and have the following in ability.rb -

can :contribute, Book do |book|
  book.contributions.where(user_id: user.id)
end

Ruby evaluates this as true whether or not the where query returns any match. How do I get the query to appropriately evaluate as false? Is this even the right approach in cancan?


Solution

  • use any? method on the records returned

    book.contributions.where(user_id: user.id) will return [](empty array) if no records are found

    book.contributions.where(user_id: user.id).any? will return true if any records are there and false otherwise