我有一个类Client
,belongs_to
另一个类Account
Account
只处理对一个帐户进行身份验证和分发一个API密钥,并且有许多类型的用户可以拥有一个帐户。我有一个before_create
回调,当Account
调用create
方法时,它会创建一个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">
发布于 2015-04-13 18:31:09
客户端模型的accepts_nested_attributes_for
设置应该自动为您处理帐户创建和关系设置。尝试取出generate_account
回调,看看这是否有帮助。
https://stackoverflow.com/questions/29612065
复制相似问题