Skip to content

Instantly share code, notes, and snippets.

@coorasse
Created May 23, 2017 08:14
Show Gist options
  • Save coorasse/0c0a773d2d215115cbd6161e9d4ddaf5 to your computer and use it in GitHub Desktop.
Save coorasse/0c0a773d2d215115cbd6161e9d4ddaf5 to your computer and use it in GitHub Desktop.
CanCanCan issue replication
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
gem 'rails', '5.1.0'
gem 'cancancan'
gem 'sqlite3'
end
require 'active_record'
require 'cancancan'
require 'cancan/model_adapters/active_record_adapter'
require 'cancan/model_adapters/active_record_4_adapter'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :orders, force: true do |t|
t.integer :customer_from_id
t.integer :customer_to_id
end
create_table :customers, force: true do |t|
t.integer :user_id
end
create_table :users, force: true do |t|
t.string :name
end
end
class Order < ActiveRecord::Base
end
class Customer < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :customers
end
class Ability
include CanCan::Ability
def initialize(user)
can :read, Order, customer_from_id: user.customers.ids
can :read, Order, customer_to_id: user.customers.ids
end
end
class BugTest < Minitest::Test
def test_wrong_query
user = User.create!
customers = Customer.create([{user: user},{user: user}])
order = Order.create(customer_from_id: customers[0].id)
ability = Ability.new(user)
orders = Order.accessible_by(ability, :read).count
assert_equal 1, orders
end
end
@coorasse
Copy link
Author

The generated query is correctly:

SELECT COUNT(*) FROM "orders" WHERE (("orders"."customer_to_id" IN (1, 2)) OR ("orders"."customer_from_id" IN (1, 2)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment