与factory_girl、rpsec 2.0和rails 3.0有关的问题=>无法让 has_one 关系很好地协同工作!
我正在运行rails 3.0、rspec 2.0 和factory_girl。这是我正在处理的简化场景:当我运行 rspec spec/models/user_spec.rb 时,用户一次只能订阅一个计划
# user.rb
class User < ActiveRecord::Base
has_one :plan
attr_accessible :login, :plan_id
end
# plan.rb
class Profile < ActiveRecord::Base
attr_accessible :plan
end
# user_factory.rb
Factory.define :user do |u|
u.login "test"
u.association :plan
end
#plan_factory.rb
Factory.define :plan do |p|
p.name "plan1"
end
我收到此错误:
失败/错误:user = Factory(:用户) SQLite3::ConstraintException:users.plan_id 可能不为 NULL
#spec/models/user_spec.rb
require File.dirname(__FILE__) + '/../spec_helper'
describe User do
it "should be valid" do
user = Factory(:user)
#User.new.should be_valid
user.should be_valid
end
end
我做错了什么?我陷入了这个非常简单的场景,这非常令人沮丧。那时 BDD 让我慢了下来!
I'm running rails 3.0, rspec 2.0 and factory_girl. Here is the simplified scenario I'm working with: a user can subscribe to only one plan at a time
# user.rb
class User < ActiveRecord::Base
has_one :plan
attr_accessible :login, :plan_id
end
# plan.rb
class Profile < ActiveRecord::Base
attr_accessible :plan
end
# user_factory.rb
Factory.define :user do |u|
u.login "test"
u.association :plan
end
#plan_factory.rb
Factory.define :plan do |p|
p.name "plan1"
end
when I run rspec spec/models/user_spec.rb I got this error:
Failure/Error: user = Factory(:user)
SQLite3::ConstraintException: users.plan_id may not be NULL
#spec/models/user_spec.rb
require File.dirname(__FILE__) + '/../spec_helper'
describe User do
it "should be valid" do
user = Factory(:user)
#User.new.should be_valid
user.should be_valid
end
end
what I'm doing wrong? I'm stuck with this very simple scenario, and it is very frustating. at that point BDD slow me down like hell!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您似乎错误地实现了
has_one
关联。has_one --belongs_to
关系中的外键应位于与具有belongs_to
指令的模型对应的表中。检查db/schema.rb
——我想您会发现plan_id
是在users
表中定义的。如果您希望User
模型有一个Plan
,则需要从users
中删除plan_id
并添加user_id
到计划
。如果您想让
Plan
拥有一个User
,请保持架构不变并将has_one :user
放入Plan
和user
中的belongs_to :plan
。It looks like you've implemented the
has_one
association incorrectly. The foreign key in ahas_one -- belongs_to
relationship should go in the table corresponding to the model with thebelongs_to
directive. Checkdb/schema.rb
-- I think you'll find thatplan_id
is defined in theusers
table. If you want theUser
model to have onePlan
, you'll need to removeplan_id
fromusers
and adduser_id
toplans
.If you'd rather make it so a
Plan
has oneUser
, keep the schema as is and puthas_one :user
inPlan
andbelongs_to :plan
inUser
.用户订阅一个计划。所以一个用户有一个计划,而一个计划又与许多用户相关。所以我想我做对了。错误发生在用户工厂。
替换
修复
了问题。
问题解决了!
A user subscribes to one plan. so a user has one plan and a plan is related to many users. So I think I got it right. the error was in the user factory.
replacing
by
fixed the issue.
Problem solved!