您可以在没有茧宝石的情况下制作嵌套表格;
假设您有一个发票表单,您希望在其中包含客户和产品的嵌套表单。您可以这样做;
<%= form_for @invoice do |f| %>
<%= f.text_field :invoice_number %>
<%= f.fields_for :customer do |c| %> // start nested form
<%= c.label 'customer name' %>
<%= c.text_field :customer_name %>
<% end %>
<%= f.fields_for :products do |p| %> // start nested form
<%= p.label 'product name' %>
<%= p.label :product_name %>
<% end %>
<%= f.submit 'save invoice', invoices_path, class: 'btn btn-primary' %>
<% end %>
在您的发票模型中:
has_one :customer
has_many :products
accepts_nested_attributes_for :customer, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :products, reject_if: :all_blank, allow_destroy: true
客户模型
belongs_to :invoice
产品型号
belongs_to :invoice
在您的控制器中:
def invoice_params
params.require(:invoice).permit(:number customer_attributes: [:id, :customer_name :_destroy], products_attributes: [:id, :product_name])
end
我使用发票作为解释,但您可以使用您拥有的任何模型/关系来更改它。但请记住遵循相同的复数形式。例如,如果您的模型中有has_many :customers 而不是has_one :customer,请记住将接受嵌套属性更改为accepts_nested_attributes_for :customers,并在您的控制器中将customer_attributes: [:id, :customer_name :_destroy] 更改为customers_attributes: [:id, :customer_name :_destroy]
最后但并非最不重要的一点是,请记住将您的 f.fields_for 也更改为模型中的任何内容,在此示例中它将变为:<%= f.fields_for :customers do |c| %>
编辑:
在某些情况下,您必须在控制器中创建实例。在控制器的新操作中,您必须执行以下操作:
def index
@invoices = Invoice.all
end
# GET /invoices/new
def new
@invoice = Invoice.new
@invoice.products.build
@invoice.build_customer
end