這就是情況。軌道上的紅寶石,factory_girl,validates_presence_of和多態關聯
寶石:導軌3.2,factory_girl 2.5.1
class House
has_one :address, :as => :addressable
validates :address, :presence => true
accepts_nested_attributes_for :address
end
class Address
attr_accessor :nested
belongs_to :addressable, :polymorhic => true
validates :addressable, :presence => true, :unless => :nested
end
該如何工作。
<%= form_for @house do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for :address do |a| %>
<%= a.hidden_field :nested %>
<%= a.label :street_address %>
<%= a.text_field :street_address %>
什麼是定義工廠的正確方法?
# does not work
Factory.define :house do |h|
h.association :address
end
# does not work
Factory.define :house do |h|
h.after_build do |record|
Factory.build(:address, :addressable => record, :nested => '')
end
end
# does not work
Factory.define :house do |h|
h.after_build do |record|
Factory.create(:address, :addressable => record, :nested => '')
end
end
因此,基本上,「特技」,讓accepts_nested_attributes_for:地址繞過驗證和建立在同一時間都記錄不factory_girl工作。目前,這個醜陋的混亂是唯一的解決方案。
home = House.new
home.name = 'On the prairie'
home.address_attributes = Factory.attributes_for(:address, :nested => '')
home.save
UPDATE 解決方案:
Factory.define :house do |h|
h.after_build do |record|
record.address = Factory.build(:address, :addressable => record)
end
end
您使用的是什麼版本的FactoryGirl?這是Rails3嗎? – 2012-02-08 05:23:59
謝謝,添加它們 – efoo 2012-02-08 05:33:28
[FactoryGirl和多態關聯]的可能重複(http://stackoverflow.com/questions/7747945/factorygirl-and-polymorphic-associations) – Thilo 2012-10-22 10:51:48