嵌套模型的form

原文參考: http://rails-bestpractices.com/posts/9-nested-model-forms

rails2.3開始,我們便使用accepts_nested_attributes_for使得嵌套模型更易于使用...
壞習慣:
class Product < ActiveRecord::Base
  has_one :detail
end

class Detail < ActiveRecord::Base
  belongs_to :product
end

<% form_for :product do |f| %>
  <%= f.text_field :title %>
  <% fields_for :detail do |detail| %>
    <%= detail.text_field :manufacturer %>
  <% end %>
<% end %>

class ProductsController < ApplicationController
  def create
    @product = Product.new(params[:product])
    @detail = Detail.new(params[:detail])

    Product.transaction do
      @product.save!
      @detail.product = @product
      @detail.save
    end
  end
end


這代碼看了就讓人不爽,還是學學NS說的,優雅的編碼...
class Product < ActiveRecord::Base
  has_one :detail
  accepts_nested_attributes_for :detail
end

<% form_for :product do |f| %>
  <%= f.text_field :title %>
  <% f.fields_for :detail do |detail| %>
    <%= detail.text_field :manufacturer %>
  <% end %>
<% end %>

class ProductsController < ApplicationController
  def create
    @product = Product.new(params[:product])
    @product.save
  end
end


上面是has_one的應用,據說還有has_many的應用-->
class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project
end

<% form_for @project do |f| %>
  <%= f.text_field :name %>
  <% f.fields_for :tasks do |tasks_form| %>
    <%= tasks_form.text_field :name %>
  <% end %>
<% end %>


這個用法在railscast里有相應的視頻,而且文字版的也有了,熱心的rails guy還翻譯成中文了..不過中文翻譯有些地方有歧義,如果英文還行的還是看英文吧:

Nested Model Form Part 1 
http://asciicasts.com/episodes/196-nested-model-form-part-1

Nested Model Form Part 2
http://asciicasts.com/episodes/197-nested-model-form-part-2

你可能感兴趣的:(F#,Ruby,ActiveRecord,Rails)