Reputation: 27222
I decided to take a different approach to mass assigning for security reasons and wanted to know if this is a safe way to do it inside of the controller?
QuestionsController
def new
@survey = Survey.find(params[:survey_id])
@question = Question.new
end
def create
@survey = Survey.find(params[:survey_id])
@question = @survey.questions.new
@question.title = params[:question][:title]
@question.description = params[:question][:description]
if @question.save
redirect_to new_survey_question_path
else
render :new
end
end
Can they change the survey_id
or any other column of the question
? Is their a better approach besides using attr_accessible
?
Upvotes: 1
Views: 60
Reputation: 11921
With Ruby 1.9, you can use the select method to slightly simplify iwiznia's solution.
enabled_attributes = [:title, :description]
@question = @survey.questions.new(params[:question].
select {|k, v| enabled_attributes.include?(k)})
Upvotes: 1
Reputation: 9225
@question.title, @question.description =
params[:question].values_at(:title, :description)
Upvotes: 2
Reputation: 1679
Ok, you could do something like..
enabled_attributes = [:title, :description]
params[:question].delete_if {|k, v| !enabled_attributes.include?(k) }
@question = @survey.questions.new(params[:question])
This deletes from the params[:question] hash all the attributes that aren't in the enabled array.
Upvotes: 2