使用从此解决方案获得的相同方法:
Use both Account and User tables with Devise
我正在尝试在保存用户后更新帐户模型上的owner_id列:
class Account < ActiveRecord::Base
has_many :users
has_secure_token
accepts_nested_attributes_for :users
validates :name, :presence => true
end
class User < ActiveRecord::Base
after_create :set_account_owner_id
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :account
validates :name, :presence => true
protected
def set_account_owner_id
self.account.owner_id = self.id
self.account.save
end
end
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_create中调用'save',但是,我一直得到相同的结果。
任何见解都表示赞赏。
答案 0 :(得分:1)
在after_create
回调中,不保证您将拥有记录ID。请改用after_commit on: create
。
因此,请致电:
,而不是致电after_create :set_account_owner_id
after_commit :set_account_owner_id, on: :create
另外,如果要使用after_commit测试代码,请记住添加test_after_commit gem。来自after_commit doc:
请注意,事务性灯具无法很好地使用此功能。 请使用test_after_commit gem来触发这些钩子 测试