少於 1 分鐘閱讀

範例

# 站點分類
class Market < ActiveRecord::Base
  acts_as_nested_set counter_cache: :children_count
end

# 商品
class Product < ApplicationRecord
  has_many :publishes, class_name: "ProductPublish"
  accepts_nested_attributes_for :publishes, allow_destroy: true
end

# 商品上架站點
class ProductMarket < ApplicationRecord
  belongs_to :product, dependent: :delete
end

第一種方式:在新增的時候建立完整項目

在新增的時候就一次把所有項目新增到資料庫 編輯時只顯示已經新增的項目

# [path] controllers/products_controller.rb
def new
  @Product = Product.new
  Market.all.each do |market|
    @Product.publishes.build(market_id: market.id)
  end
end
<!-- [path] views/products/_form.html.erb -->
<%= simple_form_for @Product do |f| %>
  <%= f.input :name %>
  <%= f.simple_fields_for :markets do |ff| %>
  	<%= ff.label :title, "Title" %>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>

第二種方式:新增/編輯皆顯示所有項目

所有項目都顯示,沒填寫的留空 手動指定哪些要新增,哪些項目要更新 這樣在新增/編輯都適用

<!-- [path] views/products/_form.html.erb -->
<%= simple_form_for @Product do |f| %>
  <%= f.input :name %>
	<%  Market.all.each do |market| %>
    <% market_model = @product.markets.find_by_market_id(market.id) || @product.markets.new %>
    <%= f.simple_fields_for :markets, market_model do |ff| %>
      <%= ff.label :title, "Title" %>
    <% end %>
  <% end	%>
  <p><%= f.submit "Submit" %></p>
<% end %>

參考

  1. http://railscasts.com/episodes/196-nested-model-form-part-1

更新時間:

留言