【问题标题】:How to render a RAILS partial with local variable f in new.js.erb?如何在 new.js.erb 中使用局部变量 f 渲染 RAILS 部分?
【发布时间】:2012-07-27 16:08:45
【问题描述】:

有一种方法可以在 js.erb 中像这样在 rails 中使用 :remote => true 来呈现 erb 页面:

$('#invoice_against_lease').html('$("<%= j render(:file => 'invoice/new.html.erb') %>")');

我们有这样的部分 _customer_quote_record:

   <%= f.input :quote_id, :label => 'Quote#:', :collection => quotes_for_invoice(@customer), :include_blank => true %>
   <%= f.hidden_field :_destroy %>  

部分在 html.erb 中呈现为这样,并传递了局部变量构建器:

<%= f.simple_fields_for :invoice_items do |builder| %>
  <%= render 'customer_quote_record', :f => builder %>
<% end %>

试过下面的代码:

$('#invoice_against_lease').html('$("<%= j render(:file => 'customer_lease_record', :f => f) %>")');

错误是"ActionView::Template::Error (undefined local variable or methodf'..."`

有没有办法在 js.erb 中渲染上面的部分?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    尝试以下方法:

    $('#invoice_against_lease').html('$("<%= j render(:partial => 'customer_lease_record', :locals => {:f => f}) %>")');
    

    这当然假设f 是在您进行此调用的任何地方定义的。如果不同,只需将:locals =&gt; {:f =&gt; f} 更改为:locals =&gt; {:f =&gt; "YOUR_VARIALBE"}

    【讨论】:

    • 同样的错误。 f 是仅存在于视图中的表单构建器。我的问题是如何将表单构建器传递给 js.erb 中的部分。
    • 啊,我明白了。不完全确定。您能否使用此处提供的答案 stackoverflow.com/questions/371147/…,并在部分内部使用 fields_for 而不是传递它?
    • 尝试了类似的解决方案(关于传递对象而不是表单生成器的另一篇类似帖子)。它确实部分起作用。但是关联丢失,导致保存父对象时失败。出现错误:子对象不能为空。不确定是什么导致关联丢失。
    【解决方案2】:

    另一种方法:

    <%=j render "invoice/new", f: f %>

    【讨论】:

      【解决方案3】:

      看看这个,我找到了解决办法:

      在 js.rjs 文件中,我重新生成了 form_for 和 fields_for 帮助器,并将 fields_for 构造函数保存在实例变量 @builder 中,然后将其传递给部分 (locals: {f: @builder...)

      js.rjs:

      <%
        @expense=Expense.new
        new_expense_detail=@expense.expense_details.build
        form_for(@expense) do |f| 
          f.fields_for(:expense_details,new_expense_detail,:child_index=>@child_index) do |builder| 
            @builder=builder # <<--- New line compared js.rjs
          end
        end
      %>
      
      $("#cost_center_group_<%=@child_index%>").html("<%= escape_javascript(render(partial: 'select_costcenter', locals: {f: @builder,child_index: @child_index}))%>");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-21
        • 2018-05-05
        相关资源
        最近更新 更多