2013-12-09 16 views
0

我有下面的代码获得原来的对象:无法从联想

account = Account.find(1) 
customer = ThirdPartyAPI.retrieve("123456") 
account.customers.import(customer) 

而这里的导入方法:

class Customer < ActiveRecord::Base 
    belongs_to :account 

    def self.import(customer) 
     # I need to get the Account ID. 
     # Have tried `self.account.id`, but it throws this: 
     # NoMethodError: undefined method `account' 
    end 
end 

从这个import方法中,我试图让主帐户ID。正如您在代码注释中看到的那样,当我尝试拨打self.account.id时,会引发NoMethodError: undefined method 'account'错误。

我的账户模型具有关联安装:

class Account < ActiveRecord::Base 
    has_many :customers 
end 

回答

0

你是不是想给客户添加到客户帐户的阵列?如果是这样,你可能要像这样做:

account.customers << customer 

,因为你不是指类Account的特定实例时不能从类方法访问self.account.id

0

您从第三方API获得的对象customer不是Customer中的持久对象。没有身份证。

您可以将其视为具有客户属性的散列。然后,您只需要执行该操作即可将其保存起来,并将account_id指定为account对象。

def self.import(customer_attr, account) 
    attr = customer_attr.merge account: account 
    customer = create attr 
end