Rails 4.2 belongs_to relation和before_create回调没有设置模型

时间:2015-04-13 18:05:04

标签: ruby-on-rails model

我有一个Clientbelongs_to另一个课Account

Account仅处理对帐户进行身份验证并输出API密钥,并且有许多类型的用户可以拥有帐户。我有一个before_create回调,当Account调用它的Client方法时会创建createClientAccount实例都已正确创建(或不),但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">

1 个答案:

答案 0 :(得分:1)

客户端模型的accepts_nested_attributes_for设置应自动为您处理帐户创建和关系设置。尝试取出generate_account回调,看看是否有帮助。