有关嵌套资源的使用,母子表单


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





<% @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

你可能感兴趣的:(表单)