【问题标题】:dynamically generated nested form with cocoon rails带有茧形导轨的动态生成的嵌套表单
【发布时间】:2020-04-20 12:23:11
【问题描述】:

我有一个带有 cocoon 的嵌套表单,但在尝试通过 JavaScript 计算我的总价格时遇到了问题。当我检查我的查看源页面时,字段中生成的属性没有值属性。如果我使用@invoice.line_items.build,则计算总价,但看不到茧的动态字段。谢谢,正在等待我能尽快得到的任何帮助。

   class InvoicesController < ApplicationController

     before_action :set_invoice,:set_line_item, only: [:show, :edit, :update, :destroy]

     def index
       @invoices = Invoice.all
     end

     def show
     end

     def new
       @invoice = Invoice.new
      @invoice.line_items.build
     end

     # GET /invoices/1/edit
     def edit

     end

     def create
       @invoice = Invoice.new(invoice_params)
       respond_to do |format|
        if @invoice.save
          format.html { redirect_to @invoice, notice: 'Invoice was successfully created.' }
          format.json { render :show, status: :created, location: @invoice }
        else
          format.html { render :new }
          format.json { render json: @invoice.errors, status: :unprocessable_entity }
        end
      end
    end

    def update
      respond_to do |format|
        if @invoice.update(invoice_params)
          format.html { redirect_to @invoice, notice: 'Invoice was successfully updated.' }
          format.json { render :show, status: :ok, location: @invoice }
        else
          format.html { render :edit }
          format.json { render json: @invoice.errors, status: :unprocessable_entity }
        end
      end
    end

    def destroy
      @invoice.destroy
      respond_to do |format|
        format.html { redirect_to invoices_url, notice: 'Invoice was successfully destroyed.' }
        format.json { head :no_content }
      end
    end


    private

    # Use callbacks to share common setup or constraints between actions.
    def set_invoice
      @invoice = Invoice.find(params[:id])
    end

    def set_line_item
      @line_item = LineItem.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.    
     def invoice_params
       params.require(:invoice).permit(:amount, :date, :currency, {line_items_attributes: 
        [:id,:quantity,:net_amount, :description, :unit_cost]})
     end

   end

 <tbody class='line_items'>
                <%= f.fields_for :line_items do |builder| %>
                <%= render 'line_item_fields', :f => builder %>
                <% end %> 
           </tbody>
      </table>
        <%= link_to_add_association 'add item', f, :line_items, class: "btn btn- 
  primary",data: {"association-insertion-node" => "tbody.line_items", "association-insertion-method" => "append"} %>
        <%= f.submit  class:"btn btn-primary" %>

  <tr class="nested-fields">
     <div class="container">
       <div class="row row-cols-5">
       <div class="col"> <td><%= f.text_field :description, class: "form-control item_desc" %></td></div><br/>
    <div class="col"> <td><%= f.text_field :quantity,  class: "form-control quantity" %></td></div><br/>
    <div class="col"> <td><%= f.text_field :unit_cost, class: "form-control unit_cost"%></td></div><br/>
    <div class="col"> <td class="price_td"><%= f.text_field  :net_amount, class: "form-control price", :readonly => true %></span> <span class= "subtotal_currency"></span></td></div><br/>
    <div class="col"> <td><%= link_to_remove_association 'Delete', f, class: 'remove_record btn btn-danger' %></td></div>
  </div>
</div>

这是javascript

  function update_price(){ 
      var row = $(this).parents('.nested-fields');
      var price = row.find('.unit_cost').val() * row.find('.quantity').val();
      price = price.toFixed(2);
      isNaN(price) ? row.find('.price').val('is not a number') : 
      row.find('.price').val(price);
      update_subtotal();

  }

【问题讨论】:

  • javascript函数update_price什么时候调用?它不工作吗?您是否使用茧回调来触发它?你能告诉我们现在怎么称呼它吗?
  • 感谢您的回复。我没有使用茧回调来触发它。当我在数量和单位成本字段上插入一个值时,会调用 update_price。该方法返回总价。但是使用茧生成的字段,update_method 似乎不起作用,当我尝试查看从茧生成的字段传递的内容时,即使通过页面源,它​​也是空白的。
  • 您能告诉我们您如何将update_price 链接到数量和单位成本字段的更改事件吗?
  • 我使用了下面的函数 function bind(){ $('.unit_cost').blur(update_price); $('.quantity').blur(update_price); }

标签: javascript jquery ruby-on-rails nested-forms cocoon-gem


【解决方案1】:

您使用以下代码附加事件:

$('.unit_cost').blur(update_price); 
$('.quantity').blur(update_price); 

但是,这只会将事件处理程序绑定到运行此命令时页面上的元素,并且有更好的方法来实现相同的效果:

$(document).on('blur', '.unit_cost, .quantity', update_price)

我将事件附加到顶级 document(因此这甚至可以兼容 turbolinks,但您也可以使用封闭的 form 或 div),我们响应 blur 事件,但前提是触发元素有类.unit_cost.quantity

【讨论】:

  • 感谢@nathanvda,我按照说明应用了更改并且它有效。插入生成的字段值后我仍然有问题,它似乎没有保存在数据库中。我只能保存“@invoice.line_items.build”方法的字段值,但不能保存 add_item 字段。它可能有什么问题。谢谢
  • 有点难说,因为您没有显示整个表单,但有一些可能的原因:使用 html-ids 而不是类(不允许重复 ids,因此它只会上传第一次出现的表单中的 id),您的 link_to_add_association 将项目添加到表单之外。我看到你在link 之前有一个&lt;/table&gt;,所以这可能会强制关闭表单(如果它是在表格内开始的)。否则,也许您应该提出另一个问题并提供更多详细信息。
  • 好的,感谢您提供的详细解释,但我的意思是 add_field 按钮没有为每个行项目生成唯一 ID,这使得它无法与第一行一起保存-项目
  • 显示发布到控制器的内容(检查日志)。如果项目已过帐到控制器,则应保存它们。我是说他们可能不是。如果您开始一个新问题,也许会更清楚,因为我不确定我是否完全理解您的新问题。把它链接在这里,我可以检查一下。
  • 好的,刚刚完成,链接是stackoverflow.com/questions/59590890/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2014-02-28
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
相关资源
最近更新 更多