---
title: "有关嵌套资源的使用，母子表单"
author: "夜鸣猪"
date: "2013-03-12T11:43:11Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-03-12T11:43:11Z"
id: 1828068
url: "https://hlee.iteye.com/blog/1828068"
---

```ruby


class Post < ActiveRecord::Base
  validates_presence_of :name, :title
  validates_length_of :title, :minimum => 5
  has_many :comments
  has_many :tags

  accepts_nested_attributes_for :tags, :allow_destroy => :true  ,
    :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end


```




```ruby


<% @post.tags.build if @post.tags.empty? %>
<% form_for(@post) do |post_form| %>
  <%= post_form.error_messages %>

  <p>
    <%= post_form.label :name %><br />
    <%= post_form.text_field :name %>
  </p>
  <p>
    <%= post_form.label :title, "title" %><br />
    <%= post_form.text_field :title %>
  </p>
  <p>
    <%= post_form.label :content %><br />
    <%= post_form.text_area :content %>
  </p>
  <h2>Tags</h2>
  <% post_form.fields_for :tags do |tag_form| %>
    <p>
      <%= tag_form.label :name, 'Tag:' %>
      <%= tag_form.text_field :name %>
    </p>
    <% unless tag_form.object.nil? || tag_form.object.new_record? %>
      <p>
        <%= tag_form.label :_destroy, 'Remove:' %>
        <%= tag_form.check_box :_destroy %>
      </p>
    <% end %>
  <% end %>

  <p>
    <%= post_form.submit "Save" %>
  </p>
<% end %>

```







<http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html>

<http://guides.rubyonrails.org/v2.3.11/getting_started.html>