我们如何在 rails 4 中创建单个 parent 模型的嵌套形式?

how can we create a nested form a single parent model in rails 4?

我有一个叫 timesheetmodel。我想要这个 timesheet 模型的嵌套形式。意味着我不想添加任何 child models 到它。基本上我想要单个 model(timesheet) 的嵌套形式。 当我点击 add button 另一个 form 应该出现在 parent model(timesheet) 同样当我们点击 removeform 应该是删除。我怎样才能做到这一点?有什么 gem 可以做到这一点吗?

我正在使用自我参照协会。

出现错误:Invalid association. Make sure that accepts_nested_attributes_for is used for :log_times association.

<%= nested_form_for(@log_time, html: {:class => 'form-inline'}) do |f| %>
    <%= f.label :date %>
    <%= f.date_select :date, { order: [:day, :month, :year] } ,{:class => 'form-control' } %>
    <%= f.fields_for :log_time do |details| %>
      <%= details.label :date %>
      <%= details.date_select :date, { order: [:day, :month, :year] } ,{:class => 'form-control' } %>
      <%= details.link_to_remove "<i class='fa fa-minus'></i>Remove".html_safe,:class=>"btn btn-danger btn-sm" ,:style=>"color: white;"%>
    <%end %>
    <%= f.link_to_add "<i class='fa fa-plus'></i>Add".html_safe, :log_times, :class=>"btn btn-primary btn-sm", :id=>"",:style=>"" %>
    <%= f.button "Submit" ,:class=>"btn btn-primary  btn-sm" do%>
      <i class='fa fa-send-o'></i>Submit
    <%end%>



<% end %>

将自引用关联添加到您的时间表模型:

class Timesheet < ActiveRecord::Base
  belongs_to :parent, class_name: 'Timesheet'
  has_many :children, class_name: 'Timesheet', foreign_key: 'parent_id'

  accepts_nested_attributes_for :children
end

在控制器中你可以做:

@timesheet = Timesheet.new
@timesheet.children.build