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 can't be blank 」という検証エラーが発生するため、: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 に答える