accepts_nested_attributes_for 在rails中,可以让嵌套表单变得很简单。
举个例子:
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提供了这样神奇的方法!~
参考资料: http://www.niancode.com/?p=268其他资料:
http://thirddirective.com/posts/8-rails-3-and-accepts_nested_attributes_for-my-mistakes
此外:
class Blog < ActiveRecord::Base
has_many :posts
has_one :author
accepts_nested_attributes_for :author, :reject_if => proc { |attributes| attributes.all? {|k,v| v.blank?} }
accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes.any? {|k,v| v.blank?} }
end
在新的ActiveRecord中支持使用
:all_blank
和 :any_blank
来代替上述代码:
class Blog < ActiveRecord::Base
has_many :posts
has_one :author
accepts_nested_attributes_for :author, :reject_if => :all_blank
accepts_nested_attributes_for :posts, :reject_if => :any_blank
end
https://rails.lighthouseapp.com/projects/8994/tickets/2501-any_blank-and-all_blank-options-for-accepts_nested_attributes_for-reject_if