我有 2 个模型:
# user.rb
class User < ActiveRecord::Base
has_one :profile, :dependent => :destroy
end
# profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
end
# user_factory.rb
Factory.define :user do |u|
u.login "test"
u.association :profile
end
我想做这个:
@user = Factory(:user)
=> #<User id: 88,....>
@user.profile
=> #<Profile id:123, user_id:88, ......>
@user = Factory.build(:user)
=> #<User id: nil,....>
@user.profile
=> #<Profile id:nil, user_id:nil, ......>
但这不起作用!它告诉我我的个人资料模型不正确,因为没有用户!(它将配置文件保存在用户之前,因此没有user_id ...)
我怎样才能解决这个问题?尝试了一切.. :( 我需要调用 Factory.create(:user)...
更新
修复了这个问题 - 现在使用:
# user_factory.rb
Factory.define :user do |u|
u.profile { Factory.build(:profile)}
end
# user.rb
class User < ActiveRecord::Base
has_one :profile, :dependent => :destroy, :inverse_of => :user
end
# profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
end