简体   繁体   中英

Rails - nested model: Can't mass-assign protected attributes

I have two models, Car and Manufacturer . These models are pretty simple:

class Car < ActiveRecord::Base
  attr_accessible :manufacturer_id, :car_name, :descr, ...
  belongs_to :manufacturer
  ...
end

and

class Manufacturer < ActiveRecord::Base
  attr_accessible :name, :url
  has_many :cars
  ...
end

The view ( views/cars/_form.html.haml ) with form for entering data:

= form_for @car do |f|
  .field
  = f.label :car_name
  = f.text_field :car_name
  ...
  = f.fields_for @manufacturer do |m|
    .field
    = m.label :name
    = m.text_field :name
    ...

When I send the form for saving entered information (it goes to CarsController ), I get this error:

Can't mass-assign protected attributes: manufacturer

I've tried to add the

accepts_nested_attributes_for :manufacturer

to the Car model, but it didn't help me...

Where is the problem?

EDIT: How I am saving data in controller:

@manufacturer = Manufacturer.new(params[:car][:manufacturer])
@car = @manufacturer.cars.build(params[:car])

EDIT2: Data from log:

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"4vcF5NV8D91DkxpCsqCzfbf05sOYsm7ssxZvPa3+kXo=",
 "car"=>{"car_name"=>"...",
 "descr"=>"...",
 "categroy_ids"=>["2",
 "3",
 "4"],
 "manufacturer"=>{"name"=>"Company",
 "url"=>"..."}},
 "commit"=>"Save",
 "id"=>"..."}

Thank you

Can you save manufacturer through car?

Add to Car model:

accepts_nested_attributes_for :manufacturer

Add manufacturer_attributes among other Car attributes to attr_accessible call in Car model:

attr_accessible :manufacturer_attributes, :car_name, :descr, ...

Save it in your controller action(standard way) something like this:

def create
  @car = Car.new(params[:car])
  if @car.save
    redirect_to @car
  else
    render :new
 end
end

Make sure that everything you are sending in manufacturer_attributes hash is white listed with attr_accessible call in Manufacturer model(:name, :url etc..).

You need to add

attr_accessible :manufacturer_id, :car_name, :descr, :manufacturer_attributtes

in car the model. Don't bother with @manufacturer in your saving method in the car controller it is taken care of.

You should read this : Active Record Nested Attributes

I hope it helped.

Your params[:car] contains manufacturer attributes.. Try this:

@manufacturer = Manufacturer.new(params[:car].delete(:manufacturer)) 
@car = @manufacturer.cars.build(params[:car])

You are not making use of has_many relation by doing this way. You can go through this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM