Search code examples
ruby-on-railsrubyruby-on-rails-3activerecordmodel-associations

Creating table entry with params hash and associated model(s) params hash


i want to do something like this:

user.items << Item.new(params[:item] , :computer => Computer.new(params[:computer] , :laptop => Laptop.new(params[:laptop])))

But this generates an error "wrong number of arguments (2 for 1)"!


Solution

  • What you're doing is actually interpreted as

    Item.new(params[:item] , {
      :computer => Computer.new(params[:computer], { 
        :laptop => Laptop.new(params[:laptop])
      })
    })
    

    #new expects a hash attribute, and you're giving it two hashes. One solution would be to merge the hashes using Hash#merge.