ruby on rails - How to prevent mass assignments on associations the right way? -
let's have model warehouse
, model car
, , model dealer
.
model car
like:
attr_accessible :make, :year belongs_to :warehouse belongs_to :dealer
controller cars
like:
def create car = current_dealer.find(params[:car][:warehouse_id]).cars.new(params[:car]) car.save! end
the view of cars#new
like:
<%= semantic_form_for @car |f| %> <%= f.inputs %> <%= f.input :warehouse, :include_blank => false %> <%= f.input :make %> <%= f.input :year %> <% end %> <% end %>
dealers can choose warehouse when adding car, above code protected against mass assignments (a.k.a. dealers adding cars warehouses don't own), raises exception saying :warehouse_id
cannot mass assigned, that's because it's brought parameters params[:car][:warehouse_id]
.
how rid of error without manually assigning attributes? , method anyways?
p.s. tried params[:car].delete(:warehouse_id)
doesn't right way this.
since :warehouse_id not mass-assignable attribute of car, can't post form attribute of car. rails raise mass-assignment error if name params in such manner if nothing them in controller.
rather doing (non formtastic specific):
<%= f.hidden_field :warehouse_id %>
do:
<%= hidden_field_tag :warehouse_id, @car.warehouse_id %>
i'm not familiar formtastic, think above line should work.
in controller:
def create @car = current_dealer.find(params[:warehouse_id]).cars.new(params[:car]) @warehouse = warehouse.find(params[:warehouse_id]) @car.warehouse = @warehouse @car.save! end
it's little more tedious, know. unfortunately, securing code requires more effort.
conclusion: params[:car][:warehouse_id]
= mass assignment
Comments
Post a Comment