Wrong Number of Arguments (2 for 1) - Rails

I'm really really stuck and annoyed by it right now.

I am running Rails 2.3.5

My View/pages/customers.html.erb just has:

 <% form_tag do %> First Name <%= text_field_tag :firstName, params[:firstName] %> Last Name <%= text_field_tag :lastName, params[:lastName] %> <%= submit_tag "Enter" %> <%end%> 

My Models/customer.rb just has:

 class Customer < ActiveRecord::Base attr_accessible :firstName, :lastName end 

My Controller/pages_controller has

 class PagesController < ApplicationController def custs @cust = Customer.new(params[:firstName], params[:lastName]) @cust.save end end 

as you can see, I'm just trying to enter two fields from the external interface, and then save them to the database. However, whenever I load my page, it gives me an error:

wrong number of arguments (2 for 1) pages_controller.rb: 3: in new' pages_controller.rb:3:in custs'

It is strange that when I use sandbox script / console, I can insert the data in order.

What's going on here? please explain to someone!

+4
source share
3 answers

http://apidock.com/rails/ActiveRecord/Base/new/class the new feature is explained a bit here. The most important part is "pass the hash with the key names matching the name of the associated column name." Instead of @cust = Customer.new(params[:firstName], params[:lastName]) you should have @cust = Customer.new(:firstName => params[:firstName], :lastName => params[:lastName]) . That should do the trick.

+7
source

A quick fix is ​​to change line 3 pages_controller to the following:

 @cust = Customer.new({:firstName => params[:firstName], :lastName => params[:lastName]}) 

Without the right keys Rails does not know what values ​​you pass and in what order.

The big problem is that your form is not configured properly. You may have a big reason for this, but if not, I would recommend creating an empty Rails project and using generate scaffold to find out how the normal Rails form / controller is configured.

+1
source

Since new accepts the hash from which the attributes will be set, where the hash has the corresponding keys, Customer.new(params) should be sufficient, shouldn't it? If the parameters do not have keys for the attributes that you do not want to set in this case, I suppose.

Obviously, your sample code may have been edited to better represent the problem, but as shown, the #new / # save pair can usually be reduced to Customer#create(params)

0
source

All Articles