I’m not familiar on how forms work.
Example Scenario
Lets say users can create surveys but after they are created cannot edit them but only add questions to them. This is done by using the edit action on the Survey.
class Survey < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions
end
class Question < ActiveRecord::Base
belongs_to :survey
belongs_to :user
end
# QuestionsController
def edit
@survey = Survey.find(params[:id])
@survey.questions.build
end
def update
@survey = Survey.find(params[:id])
@survey.update_attributes(params[:survey])
redirect_to ...
end
Then the form should be:
<%= form_for @survey do |f| %>
# No surveys fields on this form!
<% f.fields_for :questions do |builder| %>
<%= render "question_fields", :f => builder %>
<% end %>
<%= f.submit "Submit" %>
<% end %>
Now does this leave the Survey’s values vulnerable or open to hacking even if I want the survey’s fields to be unusable after creation?
What about in general? Can model values still be edited when their not on the form? What’s the logic behind this and how would I know they couldn’t?
Thanks, just a newbie trying to learn.
Yes, those attributes can still be edited by submitting them as parameters to your form, even if you don’t provide fields for them.
To protect against that, you can protect the attributes explicitly (in later versions of Rails, this is the default). In your
Surveymodel, addThis prevents mass assignments for those attributes, both for create and update. To allow creating, you’ll have to assign those attributes explicitly in the
createaction of yourSurveyController:EDIT:
As blackbird07 points out, the better approach is to whitelist those attributes that you want to allow mass-assignment for, instead of the blacklist approach described here.