简体   繁体   English

Rails模型中未​​定义的方法self.id

[英]Undefined method self.id in rails model

I have a simple Customer model which has id, firstName, lastName, address_id columns. 我有一个简单的Customer模型,其中包含id,firstName,lastName,address_id列。

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. 我使用的是Rails 2.3.5,我已经在很多书中看到了这段代码。 My Customer table does have an ID column. 我的客户表确实有一个ID列。 I've verified in actual DB. 我已经在实际数据库中进行了验证。

self.add_customer is class method, not instance method, and you have id method only in instances. self.add_customer是类方法,不是实例方法,并且仅在实例中具有id方法。

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 . 它将自动将新客户与@address关联。

Alternatively you can remove self from method definition and 或者,您可以从方法定义中删除self和

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 之所以起作用,是因为如果您将add_customer声明为实例方法(没有self或类名,例如Address.add_customer ),那么它就可以访问self.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM