检查 Factory-Girl 中的现有记录

发布于 2024-12-18 10:51:47 字数 506 浏览 3 评论 0原文

这就是我正在尝试做的事情。我有几个对象,但为了简单起见,我将其保留为两个。这两个对象具有多对一的关系。例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

彩扇题诗 2024-12-25 10:51:47

我知道这可能不是最优雅的解决方案,但这就是我的解决方案,它似乎正在做我需要的事情......

#defined in foo
def existing_foo(foo_id)
  if(Foo.find_by_FOOID(foo_id) == NIL)
    Factory(:foo, :foo_id => foo_id)
    return :foo_id
  end
  Foo.find_by_FOOID(foo_id).FOOID
end

#defined in bar
Factory.define bar do |record|
  record.sequence(:foo_id){|n|existing_foo("blah#{n}")}
end

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...

#defined in foo
def existing_foo(foo_id)
  if(Foo.find_by_FOOID(foo_id) == NIL)
    Factory(:foo, :foo_id => foo_id)
    return :foo_id
  end
  Foo.find_by_FOOID(foo_id).FOOID
end

#defined in bar
Factory.define bar do |record|
  record.sequence(:foo_id){|n|existing_foo("blah#{n}")}
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文