views:

203

answers:

3

I am really really stuck and annoyed with this right now.

I am running Rails 2.3.5

My View/pages/customers.html.erb simply 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 simply 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

so as you see I am just trying to enter two fields from front end and then save them to the DB. However, whenever i load my page it give me error:

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

weird thing is that when I use the sandbox script/console I am able to insert data fine.

What is going on here? please someone explain!

+2  A: 

http://apidock.com/rails/ActiveRecord/Base/new/class here is a little explanation of the new function. The crucial part - "pass a hash with key names matching the associated table column name". Instead of @cust = Customer.new(params[:firstName], params[:lastName]) you should have @cust = Customer.new(:firstName => params[:firstName], :lastName => params[:lastName]). This should do the trick.

Piotr Jakubowski
+1 Great answer + background
Doug Neiner
awesome answer. now I want my last hour back
Omnipresent
+1  A: 

The quick fix is to change line 3 of pages_controller to this:

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

Without proper keys Rails has no idea what values you are passing and in what order.

The bigger problem seems to be that your form is not setup properly. You might have a great reason for it, but if not, I would recommend creating a blank Rails project, and using generate scaffold to see how a normal Rails form/controller is setup.

Doug Neiner
yeah i was just playing around with it. and removed some stuff from the form to avoid verbosity. I dont like scaffolding. I could not believe that AWDR book makes use of scaffolding all the way to chapter 6!
Omnipresent
A: 

Since new takes a hash, from which attributes will be set where the hash has the corresponding keys, Customer.new(params) should be sufficient, shouldn't it? Unless params also has keys for attributes that you don't want to be set in this case, I suppose.

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

Mike Woodhouse