Rails3 gem' nested_form' - 如何选择

时间:2015-11-16 15:44:12

标签: ruby-on-rails

我添加了gem' nested_form'到Rails3应用程序。

如果要添加关联记录并输入数据,它可以正常工作。 但是,我希望关联的记录是可选的=没有输入数据。

当我保存表单时,我收到错误消息,说明相关记录缺少必填字段。

客户端型号:

  accepts_nested_attributes_for :locations

客户表格:

<%= simple_nested_form_for @client, :html => {:class => 'form-horizontal'} do |f| %>
...
        <h4>Primary Location (optional) ===========</h4>
        <%= f.fields_for :locations do |l| %>
            <%= l.input :name, :label => 'Name' %>
            <%= l.input :address1 %>
            <%= l.input :address2 %>
            <%= l.input :city %>
            <%= l.input :state %>
            <%= l.input :zipcode %>
        <% end %>
...

客户控制器:

  def new
    @client = Client.new
    @client.locations.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @client }
    end
  end

1 个答案:

答案 0 :(得分:1)

您可以使用:reject_if参数来确保包含空白必填字段的记录被拒绝。例如:

accepts_nested_attributes_for :locations, reject_if: proc { |l| l['name'].blank? && l['address1'].blank? }

查看文档以获取更多详细信息:http://api.rubyonrails.org/v3.2.19/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for

相关问题