Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 无法从关联中获取原始对象_Ruby On Rails - Fatal编程技术网

Ruby on rails 无法从关联中获取原始对象

Ruby on rails 无法从关联中获取原始对象,ruby-on-rails,Ruby On Rails,我有以下代码: 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 I

我有以下代码:

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

您是否正在尝试将客户添加到帐户的客户阵列中?如果是这样,您可能希望这样做:

account.customers << customer
您无法从类方法访问self.account.id,因为您没有引用类帐户的特定实例。

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

您可以将其视为具有customer属性的散列。然后您需要做的就是保存它,并为它分配一个帐户id作为帐户对象

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