Undefined method self.id in rails model

ruby-on-rails

Solution

`self.add_customer` is class method, not instance method, and you have `id` method only in instances.

Edit: Let assume that you have:

class Customer < ActiveRecord::Base
  belongs_to :address
end

Class Address < ActiveRecord::Base
  has_many :customers
end

Then you can:

@address.customers.create(:first_name => first_name, :last_name => last_name)

and it will automatically associate new customer with `@address`.

Alternatively you can remove self from method definition and

def add_customer(firstname, lastname)
  @cust = Customer.new(:firstName => firstname, :lastName => lastname, :address_id => self.id)
  @cust.save
end

should just work. It works because if you declare `add_customer` as instance method (without self or class name like `Address.add_customer`) then it has access to `self.id`

Problem

I have a simple Customer model which has id, firstName, lastName, address_id columns. In the method I have the following method to add data to the database: ``` def self.add_customer(firstname, lastname) @cust = Customer.new(:firstName => firstname, :lastName => lastname, :address_id => self.id) @cust.save end ``` This is giving me error ``` undefined method `id' ``` I'm using rails 2.3.5 I've seen this code working in many books. My Customer table does have an ID column. I've verified in actual DB.

Original source