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