2010-01-20 32 views
1

我有一个简单的Customer模型,它有id,firstName,lastName,address_id列。未定义的方法self.id在rails模型中

在我下面的方法将数据添加到数据库的方法:

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

这是给我的错误

undefined method `id' 

我使用的铁轨2.3.5我见过这个代码在许多书籍中工作。我的客户表具有ID列。我已经在实际的DB中验证过。

+0

“客户”是否扩展ActiveRecord :: Base? – 2010-01-20 06:07:32

回答

6

self.add_customer是类方法,而不是实例方法,并且只有在实例中才有id方法。

编辑:
让假设你有:

class Customer < ActiveRecord::Base 
    belongs_to :address 
end 

Class Address < ActiveRecord::Base 
    has_many :customers 
end 

然后,您可以:

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

,它会自动的新客户与@address关联。

或者你可以从方法定义中删除自己和

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

应该只是工作。它的工作原理是因为如果你声明add_customer作为实例方法(没有自己或类名称,如Address.add_customer),那么它有权访问self.id

+0

所以,有没有办法获得访问ID?我试图模仿我在另一个答案中看到,因此:http://stackoverflow.com/questions/1673433/how-to-insert-into-multiple-tables-in-rails/1673442#1673442 – Omnipresent 2010-01-20 16:22:24

+0

谢谢,但我有试过了。如果我从add_customer中删除自己,那么当我通过编写Customer.add_customer从我的控制器调用此方法时,它会失败,说未定义的方法add_customer .. – Omnipresent 2010-01-20 16:41:25

+0

@omnipresent为什么从控制器调用'Customer.add_customer'?你可以很容易地调用'Customer.create(:first_name => first_name,:last_name => last_name,:address => @address)',并且可以从form中给出整个参数列表,所以:'Customer.create(params [:customer ])''也可以工作 – MBO 2010-01-20 16:47:24