我尝试关注railscast 196
nested model
,但我无法让它发挥作用。 add_link_fields
无法向表单添加任何字段。我尝试使用不同的javascript
代码。他们没有为我工作。
这是客户表格,有几个订单。
<%= simple_form_for @customer , :html => {:class => 'form-horizontal' } do |f| %>
<%= f.input :first_name, :hint => 'First Name' %>
<%= f.input :last_name, :hint => 'Last Name' %>
<%= f.input :email , :hint => 'Email' %>
<%= f.input :address, :label => false, :hint => 'Address' %>
<%= f.input :customer_number, :label => false, :hint => 'Customer Number' %>
<%= f.input :birthday, :label => false, :hint => 'Birthday' %>
</div>
<div class="tab-pane fade" id="profile">
<div class="text-left">
<ul>
<%= f.simple_fields_for :orders do |builder| %>
<li class = "col-lg-4">
<p><%= render 'order_fields' , :f => builder %></p>
<li />
<% end %>
<%= link_to_add_fields "Add Question", f, :orders %>
<ul />
</div>
</div>
以下是partial
,_order_fields
:
<%= f.input :order_number , :label => false , :hint => 'Number' %>
<%= f.input :order_date, :as => :string , :label => false, :hint => 'Date' %>
<%= f.input :sum , :label => false , :placeholder => 'Sum', :hint => 'Sum'%>
<%= f.hidden_field :_destroy %>
这是customer controller
的新动作:
def new
@customer = Customer.new
@customer.orders.build
end
和set_params
操作在此处:
def customer_params
params.require(:customer).permit(:id, :first_name, :last_name, :email, :address, :birthday, :customer_number, :orders_attributes => [:id, :order_number, :order_date, :sum, :customer_id,:quantity_of_product,:quantity,:list_of_products])
end
和javascript
:
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
最后是辅助方法:
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
这是我的customer model
:
class Customer < ActiveRecord::Base
has_many :orders
has_and_belongs_to_many :products
accepts_nested_attributes_for :orders, :allow_destroy => true
end
我也尝试了其他几个javascript
,他们中的其他人无法帮助我。我在这里缺少什么?我编辑了这个问题。