2014-03-04 71 views
5

有以下工廠:FactoryGirl attributes_for與各協會

factory :car do 
    name 'Some car' 
    engine_value 1.6 
    color '#ff0000' 
    car_type 
    engine_type 
    transmission 
    drive_type 
    material 
end 

正如你看到有很多的關聯對象。但代碼

attributes_for(:car) 

只生成:name=>"Some car", :engine_value=>1.6, :color=>"#ff0000"}散列。我需要獲得一個包含所有屬性的散列。我該怎麼做?謝謝。

+0

可能重複[FactoryGirl:爲什麼屬性\ _for忽略一些屬性?](http://stackoverflow.com/questions/10290286/factorygirl-why-does-attributes-for-omit-some-attributes) – Chowlett

+0

另請參閱:http://stackoverflow.com/questions/5103572/factorygirl-attributes-for-not-giving-me-associated-attributes –

回答

11

我碰到同樣的問題,我已經用類似

build(:car).attributes 

不知道這是做的最好的方式,但它爲我工作

希望這有助於

0

您可能想要省略id,created_atupdated_at屬性。

FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at')

如果需要的鑰匙,是符號(如在由attributes_for產生的鍵):

FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at').symbolize_keys

限制:

  • 它不會產生屬性HMT和HABTM關聯(因爲這些關聯存儲在連接表中,而不是實際的屬性)。
  • 工廠中的關聯策略必須爲create,如association :user, strategy: :create所示。如果你不明智地使用它,這個策略會使你的工廠變得很慢。