Search code examples
ruby-on-railsactiverecordnested-attributes

Which is the right way to pass nested parameters to a build method ? (Ruby on Rails 5)


I am building a very simple application managing users and keys. Keys are nested attributes of a user. I am inspired by RailsCast #196. The models are defined as:

class User < ApplicationRecord
  #Validations
  ---  
  #Relations
  has_many :keys, :dependent => :destroy
  accepts_nested_attributes_for :keys, :reject_if => :all_blank, :allow_destroy => true
end

class Key < ApplicationRecord
  #Validations
  ---
  #Relations
  belongs_to :user
end

The users controller includes strong parameters:

def user_params
  params.require(:user).permit(:nom, :prenom, :section, :email, :password, keys_attributes: [:id, :secteur, :clef])
end

And I wish to initialize 1 key for each new user (users controller):

# GET /users/new
def new
  @user = User.new
  key = @user.keys.build({secteur: "Tous", clef: "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678"})
end

I tried many ways to initialize the user's key, but I can't figure out how to pass parameters to it. User is always created, but the first key is not. No error message is issued.


Solution

  • Remove the '{' tags inside the build method parameters. Should be:

    key = @user.keys.new(secteur: "Tous", clef: "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678")
    

    Also, the build method is just an alias for 'new' and used to behave differently on rails 3 apps so I've always strayed away from it and just use the more familiar 'new' method. Obviously don't forget to then save the object at some point in your controller.