Gbeschbacher
Gbeschbacher

Reputation: 456

Cancancan with custom where_condition syntax on specific tables/columns

Imagine the following setup:

ActiveRecord::Schema.define do
  create_table :books, force: true  do |t|
    t.jsonb :tags
  end
end

class Book < ActiveRecord::Base
end

class Ability
  include CanCan::Ability

  def initialize(user)
    can :read, Book, tags: user.tags
  end
end

Calling Book.accessible_by(ability, :read).to_sql would result in something like: SELECT books.* FROM books WHERE tags IN ("foo", "bar"). This behaviour is totally understandable and correct. However, I'd like to achieve something like this:

If i try to access books.tags, I always want a Query looking like: SELECT * FROM books WHERE (tags @> '["foo", "bar"]'). I would like to make use of the Postgres Jsonb Operator available and build some kind of Intersection. Is it possible to somehow hook into the Gem and e.g. patch a Method where the conditions are built and where i do some kind of hardconding like: if model == X && column == y build the condition like this, else go back the default way.

I explicitly do not want to work with custom scopes like can :read, Book, Book.custom_scope(user.tags) due to the inability of merging Abilities when defined multiple times. I want to be able to use the hash syntax.

Is there any chance i can achieve this?

Upvotes: 2

Views: 88

Answers (0)

Related Questions