2016-10-10 8 views
0

私は、2つのモデルの間に 'many-to-many'の関係を表すための結合テーブルを作成しました(has_many: throughアソシエーション付き)。ジョイン・テーブル・モデル用のファブリックを作成する必要がありますか?

私は今テストを書いています。私は、その結合テーブルモデル用のFabricatorを作成する必要があるのでしょうか?私の結合テーブルは2つの関連するモデルの外部キーしか持っていません。

答えて

1

テストで作成するモデルの工場が本当に必要です。

あなたが持っている場合たとえば:

class User 
    has_many :user_projects 
    has_many :projects, through: :user_projects 
end 

class UserProject 
    belongs_to :user 
    belongs_to :project 
end 

class Project 
    has_many :user_projects 
    has_many :users, through: :user_projects 
end 

を必要なときにActiveRecordの参加モデルを作成するようあなたは本当にUserProjectのファクトリを必要としません。

Fabricator(:user) do 
    projects(count: 3) 
end 

Fabricator(:project) do 
    user 
end 

「ピボット」モデルは、単純なテーブルを結合するよりも、より多くので、独自の属性を持っている場合しかし、多くの場合、そのオブジェクトの工場を持っていると便利です:

class User 
    has_many :lists 
    has_many :tasks, through: :lists 
end 

class List 
    belongs_to :user 
    has_many :tasks 
end 

class Task 
    belongs_to :list 
    has_one :user, through: :list 
end 

Fabricator(:list) do 
    name { 'Shopping List' } 
    user 
    tasks(count: 3) 
end 
+0

そうでもない最高世界の例 - すべてのコーヒーから... – max

+0

それは感謝の感謝@maxを作る。しかし、「ActiveRecordが必要に応じて結合モデルを作成するので、UserProjectのファクトリは本当に必要ありません」と言うと、 '' 'has_many:through'''関連の場合もそうですか? –

+1

はい、 'user.projects.create'または' project.users.create'を実行する最初の例では、 'user_projects'にレコードを挿入します。 – max

関連する問題