1

我有以下型号:

class Activity < ActiveRecord::Base
  has_many  :clientships, :dependent => :destroy
  has_many  :clients, :through => :clientships
end

class Clientship < ActiveRecord::Base
  belongs_to  :client
  belongs_to  :activity

  validates_presence_of :client_id
  validates_presence_of :activity_id, :unless => :new_record?
end

class Client < ActiveRecord::Base
  has_many  :clientships
  has_many  :activities, :through => :clientships
end

我无法创建 :activity 工厂,因为我收到验证错误“活动不能为空白”。

我的工厂是这样的:

Factory.define :activity do |a|
  a.association :staff, :factory => :user
  a.clientships { |cs| [cs.association :clientship] }
end

Factory.define :clientship do |cs|
  cs.association(:client)
end

Factory.define :client do |c|
  c.first_name {Factory.next(:name)}
  c.last_name {Factory.next(:name)}
end

当我在我的规范中运行这个工厂时出现错误: @activity = Factory(:activity)

请帮忙!

4

1 回答 1

3

在这种情况下,我总是做的事情是:

Factory.define :activity do |a|
  #whatever attributes
end

Factory.define :clientship do |cs|
  cs.association(:client)
  cs.association(:activity)
end

Factory.define :client do |c|
  c.first_name {Factory.next(:name)}
  c.last_name {Factory.next(:name)}
end

所以在我的测试/规格中我使用

Factory :clientship

也许它不是那么干净,但对我来说更有意义......但是我不确定从连接表创建这样的关系是一个好主意。

而且,总的来说,我更喜欢从belongs_to侧面创建工厂中的关联,因为最终它对我来说问题更少。

于 2010-09-24T08:18:23.217 回答