【译】嵌套的模型表单

Saturday, July 24, 2010

原文: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

Product和Detail模型是一对多的关联, 我们想创建一个产品同事创建一个新的制造商,在这个例子中,
我们创建一个product对象和一个detail对象,
然后通过事务关联他们,但是为什么我们在控制器中做这样复杂的创建,产品模型应该负责创建产品的详情。

重构...

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

我们在产品模型中添加了accepts_nested_attributes_for定义, 这样产品模型就能负责产品详情模型对象的创建了,
这样是不是很酷呢 同时我们也可以在一对多的模型关系中通过 accepts_nested_attributes_for来简化关联对象的创建

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

感谢rails提供了这样神奇的方法!~

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top