user938363
user938363

Reputation: 10350

How to render js.erb file in a string for Rails 3.2?

Here is the code new.js.erb file for Rails 3.2 app:

<% if params[:order][:field_changed] == 'quote_id' && @digi_keys.present? %>
  <% @quote_ids.each_with_index do |v, i| %>
    <% quote = PurchaseOrderx.quote_class.find_by_id(v)%>
    <% if quote %>
      $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_product_name').val("<%=quote.product_name%>");
      $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_product_spec').val('<%=quote.product_spec%>');
      $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_unit_price').val('<%=quote.unit_price%>');
      $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_unit').val('<%=quote.unit%>');      
    <% else %>
      $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_product_name').val('');
      $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_product_spec').val('');
      $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_unit_price').val('');
      $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_unit').val('');
    <% end %> 
    $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_qty').val('');
    $('#order_order_items_attributes_' + <%=@digi_keys[i]%> + '_item_note').val(''); 
    $('#order_po_total').val('');  
  <% end %>
  $('#order_field_changed').val('');
<% end %>

What we are trying to do is to save the code above into a string of js_erb_code and render it. Since the js_erb_code is mixing both jquery/javascript and erb code together, we are not sure which render option we should use in new.js.erb?

<% render inline: js_erb_code %>

Or

<% render js: js_erb_code %>

Or is this kind of coding practice problematic?

Upvotes: 0

Views: 480

Answers (1)

isaacsloan
isaacsloan

Reputation: 885

Yeah your js.erb should work fine as long as your not mixing in html as well. You can use this to turn it into a string:

erb  = ERB.new("js_erb_code")
render erb.result

Upvotes: 1

Related Questions