accepts_nested_attributes_for停止我的子表单呈现?

时间:2011-03-15 13:23:29

标签: ruby-on-rails ruby-on-rails-3

我有两个模型,商业和地址之间的关联。企业有registered_address的地方。我这样做了如下。

class Business < ActiveRecord::Base  
    has_one :registered_address, :class_name => "Address", :foreign_key => :business_registered_address_id
    accepts_nested_attributes_for :registered_address
end

class Address < ActiveRecord::Base
    belongs_to :business
end

此协会适用于我的目的。当我使用:

渲染表单时
= form_for @business do |form|
  = form.inputs :name => "Registered address" do
    = form.fields_for :registered_address do |address|
      = address.input :postcode
      = address.input :line_1
      = address.input :line_2
      = address.input :line_3
      = address.input :town
      = address.input :county

不显示任何内容,只显示空字段集。

当我在Business模型中注释掉accepts_nested_attributes_for行时,它会正确显示(但不保存)所有字段。

谁能看到我做错了什么?

谢谢

2 个答案:

答案 0 :(得分:6)

在控制器中写入此操作(我认为new

def new
  @business = Business.new
  @business.build_registered_address
  ...
end

或以您的格式@business.registered_address.new

= form_for @business do |form|
  = form.inputs :name => "Registered address" do
    = form.fields_for :registered_address, @business.registered_address.new do |address|
      = address.input :postcode
      = address.input :line_1
      = address.input :line_2
      = address.input :line_3
      = address.input :town
      = address.input :county

答案 1 :(得分:1)

form.fields_for为@ business.registered_adress中的每个对象呈现其块。如果您的数组是空的,则无显示。

您可以在控制器上编写:

@bussines.registered_address.new

然后应用程序将显示所有表单

希望这有帮助