检查 Factory-Girl 中的现有记录
这就是我正在尝试做的事情。我有几个对象,但为了简单起见,我将其保留为两个。这两个对象具有多对一的关系。例如:
class Foo < ActiveRecord::Base
has_many :bars
set_primary_key :BLAH
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
Factory.define :foo
blahblahblah
end
Factory.define :bar do |t|
t.association :foo
end
现在我想知道的是,如果我创建 bar 的实例(这将创建 foo 的实例),并且测试完成/失败/无论数据库中保留的记录是什么(按设计)。现在,如果我再次运行相同的测试,我会收到一个 SQL 错误,指出数据库中已存在主键。我想知道的是如何检查数据库中是否已存在 foo 的实例,如果是,则跳过尝试创建它并继续创建 bar ?这对你来说够模糊吗? :)
Here's what I'm attempting to do. I have several objects but for simplicity's sake I'll keep it to two. The two objects have a many to one relationship. For instance:
class Foo < ActiveRecord::Base
has_many :bars
set_primary_key :BLAH
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
Factory.define :foo
blahblahblah
end
Factory.define :bar do |t|
t.association :foo
end
Now what I want to know is if I create an instance of bar, (which will create an instance of foo), and the test finishes/fails/whatever the records remain in the database (by design). Now if I ran that same test again I would get a SQL error saying that primary key already exists in the db. What I want to know is how can I check to see if an instance of foo already exists in the db and if so skip trying to create it and continue with the creation of bar? Is that murky enough for you? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道这可能不是最优雅的解决方案,但这就是我的解决方案,它似乎正在做我需要的事情......
I know it may not be the most elegant solution but this is what I worked out and it seems to be doing what I need it to...