Reputation: 2657
previous rails 4 I had in a model
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
...
end
But now strong_parameters
replaced the protected_attributes
so I comment it and use permit
.
Now I discovered that I can access attribute without permitting it.
In rails c
I manage to do this:
2.0.0p247 :002 > User.new(admin: "1")
=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil, password_digest: nil, remember_token: nil, admin: true>
2.0.0p247 :016 > user = User.new(name: 'Nir', email: '[email protected]', password: 'foobar', password_confirmation: 'foobar', admin: "1")
=> #<User id: nil, name: "Nir", email: "[email protected]", created_at: nil, updated_at: nil, password_digest: "$2a$10$xVnY8ydd5SoaLVipK5j4Del40FrOmu4bKypGjBEwvms7...", remember_token: nil, admin: true>
When obviously I should not be able to set and change the admin attribute. Only user.toggle(:admin)
should be able to.
So what am I not understanding or should do right. And how to make this test pass:
describe "accessible attributes" do
it "should not have allow access to admin" do
expect do
User.new(admin: "1")
end.to raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
end
Upvotes: 1
Views: 418
Reputation: 2361
To prevent a user from setting the admin
property, you should not add it as a parameter of the permit
method.
params.require(:user).permit(:name, :whatever_else_you_allow)
Keywords in this are: params
(it deals with parameters) and permit
(you tell rails which properties to allow for).
Strong Parameters
will make Action Controller parameters forbidden to be used in Active Model mass assignment until they have been whitelisted. In your test however, you set the property directly on the model. Nothing prevents you from doing that.
Upvotes: 1