嵌套模型railscast 196不起作用

时间:2014-05-27 07:08:09

标签: ruby-on-rails model nested

我尝试关注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,他们中的其他人无法帮助我。我在这里缺少什么?我编辑了这个问题。

2 个答案:

答案 0 :(得分:0)

我和你一样经历了Railscast 196,link_to_add_fields帮助方法对我不起作用。相反,我选择cocoon,这很容易做到这一点。 Cocoon提供了两种辅助方法:

link_to_add_associationlink_to_remove_association

并且使用simple_formstandard rails formsformtastic

获得了一个完整的示例

遵循示例

更容易

答案 1 :(得分:0)

我创建了一个用于嵌套模型表格的仓库,这些表格来自与轨道5兼容的轨道铸件196/197。

link

上查看