Besides moving attribute whitelisting to the controller rather than the model,
Rails 4’s move to
Strong Parameters
over attr_accessible
provides great documentation about the data with which
records are being created.
Here is an example of a controller many of us have written, using
strong_parameters
:
class CommentsController < ApplicationController
respond_to :html
def create
@comment = Comment.create(comment_params)
respond_with @comment
end
private
def comment_params
params.
require(:comment).
permit(:body).
merge(user: current_user, commentable: commentable)
end
def commentable
# find and return a commentable record
end
end
Notice how the comment_params
method tells you at a glance what object’s
parameters this controller/action cares about (comment
), the specific data
being used (body
), and the extra information being added. After glancing at
the method, you hardly have to concern yourself with the rest of the class:
everything just makes sense.
strong_parameters
will be standard in Rails 4.0, but they can be used now in
Rails 3.