以嵌套形式计算添加的字段(cocoon)

时间:2016-08-03 11:07:16

标签: ruby-on-rails ruby-on-rails-4 render nested-forms cocoon-gem

我使用cocoon gem获得了一个嵌套表单:

_form.html.haml:

= simple_form_for @day do |f|
  #task
    = f.simple_fields_for :tasks do |task|
      = render 'task_fields', f: task
    .links
      = link_to_add_association '+ Aufgabe', f, :tasks
  = f.submit

_task_fields.html.haml:

.nested-fields
  = f.input :description, label: 'Name/Beschreibung: '
  = f.input :ur, as: :range, input_html: { min: '1', max: '4', id: "rangeInput#{@x}", oninput: "rangeOutput#{@x}.value = rangeInput#{@x}.value"}
  %output#rangeOutput{:for => "rangeInput#{@x}", :name => "rangeOutput#{@x}"} 3

  = link_to_remove_association "remove task", f

days_controller.rb:

def create
  @day = current_user.days.build(day_params)
  @day.save
  respond_to do |format|
    if @day.save
      format.html { redirect_to @day, notice: 'Day was successfully created.' }
      format.json { render :show, status: :created, location: @day }
    else
      format.html { render :new }
      format.json { render json: @day.errors, status: :unprocessable_entity }
    end
  end
end

我需要增加一个可变的时间,_task_fields-partial呈现或link_to_add_association被按下。

2 个答案:

答案 0 :(得分:0)

创建迁移并将列:view_count添加到嵌套属性中。

nested attribute的控制器中,在create方法中添加以下行:

@day.increment!(:view_count) 

每次调用create方法时,这将增加1。我不知道你想如何显示数字,但在视图中你可以这样做:

<%= @day.view_count %>

或者你可以使用@day.tasks.count来计算你的数量。

答案 1 :(得分:0)

根据您的需要,您可以在css中解决此问题。因此,如果您想显示行/项目编号,但实际上该编号与您无关,您可以执行以下操作:Auto-number table rows?

否则您将需要使用js回调,在插入或删除时,您可以计算并显示数字。例如,您可以使用它来限制允许的嵌套项的最大数量:https://github.com/nathanvda/cocoon/wiki/How-to-limit-the-number-of-nested-fields