Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In permitted_attributes, switch from database column detection to Rails attributes detection. Addresses #838 #839

Merged
merged 5 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/cancan/ability/strong_parameter_support.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def get_attributes(rule, subject)
klass = subject_class?(subject) ? subject : subject.class
# empty attributes is an 'all'
if rule.attributes.empty? && klass < ActiveRecord::Base
klass.column_names.map(&:to_sym) - Array(klass.primary_key)
klass.attribute_names.map(&:to_sym) - Array(klass.primary_key)
else
rule.attributes
end
Expand Down
22 changes: 17 additions & 5 deletions spec/cancan/ability_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@
describe CanCan::Ability do
before(:each) do
(@ability = double).extend(CanCan::Ability)

connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:named_users) do |t|
t.string :first_name
t.string :last_name
end
end

unless defined?(NamedUser)
class NamedUser < ActiveRecord::Base
attribute :role, :string # Virtual only
end
end
end

it 'is able to :read anything' do
Expand Down Expand Up @@ -651,13 +666,10 @@ def active?
end

it 'returns an array of permitted attributes for a given action and subject' do
user_class = Class.new(ActiveRecord::Base)
allow(user_class).to receive(:column_names).and_return(%w[first_name last_name])
allow(user_class).to receive(:primary_key).and_return('id')
@ability.can :read, user_class
@ability.can :read, NamedUser
@ability.can :read, Array, :special
@ability.can :action, :subject, :attribute
expect(@ability.permitted_attributes(:read, user_class)).to eq(%i[first_name last_name])
expect(@ability.permitted_attributes(:read, NamedUser)).to eq(%i[id first_name last_name role])
expect(@ability.permitted_attributes(:read, Array)).to eq([:special])
expect(@ability.permitted_attributes(:action, :subject)).to eq([:attribute])
end
Expand Down
Loading