Under rails 3.1 If I create a fresh new rails project, and scaffold a new resource like this:
rails g scaffold User name:string email:string
The create action will be like this by default:
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
...
else
...
end
end
end
what I am wondering is, since there is no attr_accessible defined in User model, why this create would work if I post the form to this action. Since attr_accessible will allow mass-assign, but what’s the default here?
The default in Rails is that mass assignment of any database attributes is allowed, you will not need to define that name and email string within the context of attr_accessible for them to able to be mass-assigned.
Now, attr_accessible is useful if you wish to define a whitelist of attributes that could be massed assigned, if attr_accessible is defined, then only the attributes within attr_accessible will be mass-assigned.
Similarly, attr_protected is used to define blacklist of attributes that cannot be used in mass assignment.
None of these things take place unless you define these properties however, that’s why your code works fine without attr_accessible. I personally perfer whitelist approach over the blacklist approach simply because it’s much more secure. Although your application works without attr_accessible, in the end, it is advised you use them anyways as a security precaution.