2017-01-22 35 views
1

已經翻閱並嘗試了大多數例子,仍然無法創建工作HABTM。無論如何構建CaseTrackCaseTrackValue工廠,我都無法在CaseTrack中找到CaseTrackValue[]。不應在CaseTrack中正確創建CaseTrack提供CaseTrackValue參數。
BTW:HABTM的唯一工作關聯似乎是在CaseTrack中加入HABTM Association with FactoryGirl

case_track_values { |a| [a.association(:case_track_value)] }

class CaseTrack 
has_and_belongs_to_many CaseTrackValue 
end 

class CaseTrackValue 
has_and_belongs_to_many CaseTrack 
end 

Rspec 
it 'may exercise the create action' do 
    post '<route>', params: {case_track: attributes_for(:case_track)} 
end 
end 

class CaseTrackController < ApplicationController 
private: 
    def case_track_params 
    params.require(:case_track).permit(:name, :active, {case_track_values:[]}) 
    end 
end 

回答

0

看看在我的一個項目中工作的HABTM工廠。我把整個設置放在一個常見的例子中,你可以更深入地理解它,其他stackoverflowers可以很容易地調整這個例子的用例。

所以我們有書和類別。可能有許多類別的書籍,並且可能有許多類別的書籍。

型號/ book.rb

class Book < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
end 

型號/ category.rb

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :books 
end 

工廠/ books.rb

FactoryGirl.define do 
    factory :book do 

    # factory to create one book with 1-3 categories book belongs to 
    factory :book_with_categories do 
     transient do 
     ary { array_of(Book) } 
     end 
     after(:create) do |book, ev| 
     create_list(:category, rand(1..3), books: ev.ary.push(book).uniq) 
     end 
    end 

    #factory to create a book and one category book belongs to 
    factory :book_of_category do 
     after(:create) do |book, ev| 
     create(:category, books: [book]) 
     end 
    end 
    end 
end 

個工廠/ categories.rb

FactoryGirl.define do 
    factory :category do 

    #factory to create category with 3-10 books belong to it 
    factory :category_with_books do 
     transient do 
     ary { array_of(Category) } 
     num { rand(3..10) } 
     end 
     after(:create) do |cat, ev| 
     create_list(:book, ev.num, 
      categories: ev.ary.push(cat).uniq) 
     end 
    end 
    end 
end 

helper方法,你必須把spec/support某處,然後包括它在你需要它:

# method returns 0-3 random objects of some Class (obj) 
    # for example 0-3 categories for you could add them as association 
    # to certain book 
    def array_of(obj) 
    ary = [] 
    if obj.count > 0 
     Random.rand(0..3).times do 
     item = obj.all.sample 
     ary.push(item) unless ary.include?(item) 
     end 
    end 
    ary 
    end