Ruby on rails 创建后的rails不更新父模型

Ruby on rails 创建后的rails不更新父模型,ruby-on-rails,ruby,rspec,Ruby On Rails,Ruby,Rspec,使用从该解决方案中获得的相同方法: 保存用户后,我正在尝试更新帐户模型上的owner_id列: 帐户模型 测试失败,出现以下错误: 1) Account should create an Account and a User through accepts_nested_attributes_for Failure/Error: account.owner_id.should == account.users[0].id expected: 1

使用从该解决方案中获得的相同方法:

保存用户后,我正在尝试更新帐户模型上的owner_id列:

帐户模型 测试失败,出现以下错误:

1) Account should create an Account and a User through accepts_nested_attributes_for
     Failure/Error: account.owner_id.should == account.users[0].id
       expected: 1
            got: nil (using ==)
在阅读其他线程时,我认为问题是由于我没有在after_create中调用“save”,然而,我一直得到相同的结果


任何见解都将不胜感激

创建
回调后,不能保证您将拥有记录的id。在提交后使用
:改为创建

因此,不要在创建后调用
:设置帐户\u所有者\u id
,而是调用:

after_commit :set_account_owner_id, on: :create
另外,如果您使用after_commit测试代码,请记住添加test_after_commit gem。从:

请注意,事务性装置不能很好地使用此功能。 请用宝石把这些钩子射进去 测试


您是否尝试在关联定义上传递
逆\u选项?成功。谢谢Dub我需要更多的了解。谢谢。杜布我会尝试两个建议,并让你知道。杜布想确保你得到信用。对于那些正在寻找一些额外见解的人来说:这消除了我在别处跟踪的一个讨厌的bug。有关提交后的详细信息,请参阅
class AccountsController < ApplicationController

  def new
    # Create a new Account and then update owner_id with User profile id
    @account = Account.new
    @account.users.build
  end

  def create
    @account = Account.new(account_params)
    if @account.save
      flash[:success] = "Account successfully created!"
      redirect_to accounts_path
    else
      render 'new'
    end
  end

  private

  def account_params
    params.require(:account).permit(:name, :token, :token_flag, :owner_id, users_attributes: [:name, :email, :password, :password_confirmation, :role])
  end

end
RSpec.describe Account, type: :model do
  it "should create an Account and a User through accepts_nested_attributes_for" do
    @accountuser = {
      :name => "My App Name",
      :users_attributes => [{
          :name     => "John Doe",
          :email    => "jdoe@email.com",
          :password => "password",
          :password_confirmation => "password",
          :role => "dev",
        }]
      }

    account = Account.create!(@accountuser)
    account.owner_id.should == account.users[0].id
  end
end
1) Account should create an Account and a User through accepts_nested_attributes_for
     Failure/Error: account.owner_id.should == account.users[0].id
       expected: 1
            got: nil (using ==)
after_commit :set_account_owner_id, on: :create