8

There is a way to render a erb page in js.erb like this with :remote => true in rails:

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

We have a partial _customer_quote_record like this:

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

The partial is rendered in html.erb as this, with passing local variable builder:

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

Tried the code below:

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

And the error is "ActionView::Template::Error (undefined local variable or methodf'..."`

Is there a way to render the partial above in js.erb?

user938363
  • 9,990
  • 38
  • 137
  • 303

3 Answers3

15

Try the following:

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

This of course assumes that f is defined wherever you make this call. If it's different, just change :locals => {:f => f} to :locals => {:f => "YOUR_VARIALBE"}

Naty722
  • 431
  • 4
  • 12
  • 7
    Same error. f is the form builder which lives in the view only. My question is how to pass the form builder into the partial in js.erb. – user938363 Jul 27 '12 at 19:00
  • Ah, I see now. Not entirely sure. Could you use the answer provided here, http://stackoverflow.com/questions/371147/rails-ajax-my-partial-needs-a-formbuilder-instance, and just use `fields_for` inside the partial rather than passing it? – Naty722 Jul 27 '12 at 19:20
  • Tried a similar solution (another similar post about pass object instead of form builder). It did work partially. However the association lost, which caused the failure when saving the parent object. Got error: child object can't be blank. Not sure what causes the association loss. – user938363 Jul 27 '12 at 20:31
6

Another way to do it:

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

MatayoshiMariano
  • 2,026
  • 19
  • 23
2

Look at this, I found a solution:

in js.rjs file, I repdroduce the form_for and fields_for helper, and save the fields_for constructor in a instance variable @builder, and then I pass it to the partial (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}))%>");
Albert Català
  • 2,026
  • 2
  • 29
  • 35