我有一个Client
课belongs_to
另一个课Account
Account
仅处理对帐户进行身份验证并输出API密钥,并且有许多类型的用户可以拥有帐户。我有一个before_create
回调,当Account
调用它的Client
方法时会创建create
。 Client
和Account
实例都已正确创建(或不),但account_id
列未设置。
相关代码如下:
class Client < ActiveRecord::Base
belongs_to :account, ->{includes :api_key}
accepts_nested_attributes_for :account
before_create :generate_account
private
def generate_account
self.account = Account.create(password: :password, password_confirmation: :confirm_password)
end
end
在rails控制台中,我运行Client.create("email"=>"XXXXXXX", "account_attributes"=>{"password"=>"password","password_confirmation"=>"password"})
输出如下:
(24.5ms) BEGIN
SQL (29.4ms) INSERT INTO `accounts` (`password_digest`, `created_at`, `updated_at`) VALUES ('XXXXXXXXXX', '2015-04-13 17:50:36', '2015-04-13 17:50:36')
Client Exists (29.6ms) SELECT 1 AS one FROM `clients` WHERE `clients`.`account_id` IS NULL LIMIT 1
SQL (32.1ms) INSERT INTO `clients` (`email`, `created_at`, `updated_at`) VALUES ('XXXXXXX', '2015-04-13 17:50:36', '2015-04-13 17:50:36')
(42.0ms) COMMIT
控制台输出这个作为响应:#<Client id: 6, email: "XXXXXXXXX", account_id: nil, created_at: "2015-04-13 17:50:36", updated_at: "2015-04-13 17:50:36">
答案 0 :(得分:1)
客户端模型的accepts_nested_attributes_for
设置应自动为您处理帐户创建和关系设置。尝试取出generate_account
回调,看看是否有帮助。