ruby on rails,factory_girl,validates_presence_of和多态关联

时间:2012-02-08 05:15:15

标签: ruby-on-rails ruby factory-bot

情况就是这样。

Gems:rails 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

1 个答案:

答案 0 :(得分:3)

您的第二次FactoryGirl尝试已接近,但您需要对该内置地址执行某些操作。

FactoryGirl.define do

  factory :house do
    after_build do |house|
      house.address = Factory.build(:address)
    end
  end

end