Question

I have a user who has_many services:

class User < ActiveRecord::Base
  has_many :services
  accepts_nested_attributes_for :services, :reject_if => lambda { |s| s[:name].blank? }, :allow_destroy => true
end

Here is my controller actions (devise)

def new
  build_resource({})
  5.times { resource.services.build }
  ...
end

def create
  build_resource(sign_up_params)
  resource.services.build(sign_up_params[:services_attributes])
  ...
end

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up) do |u|
    u.permit(:email, :password, :password_confirmation,
    services_attributes: [:name])
  end
end

When I submit my form here is the related params hash:

{...,
 "services_attributes"=>{
   "0"=>{"name"=>"Test"},
   "1"=>{"name"=>""},
   "2"=>{"name"=>""},
   "3"=>{"name"=>""},
...}

Giving me the following error:

unknown attribute: 0

In that case I don't know how to save multiple objects with strong parameters. The idea I have is to do something like this:

in my create method:

resource.services.build(sign_up_params[:services_attributes][:id])

It saves objects but I am not feeling ok with this... Thanks for your explaination!

Was it helpful?

Solution

It should be only:

def create
  build_resource(sign_up_params)
  ...
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top