Render Form partial from Ajax in rails

Viewed 3625

I have a form as image below:

Form with partial

Then I want to render this partial from ajax call: from .js.erb. But I don't know how to pass object to f from partial. See the image below:

how can I pass object to f:

file .js.erb

3 Answers

I was pondering on how to replace part of the form (if that is what you are doing) for a while. The following is not perfect but "works for me".

We instantiate the form builder f in the controller (instead of a view) and render only your partial into a string. Then escape and render js into Ajax reply as usually.

  def show
    respond_to do |format|
      format.js do
        helpers.form_for(@journal) do |f|
          out = render_to_string partial: 'journal_entry_transaction_fields', locals: {f: f}
          render js: %($('.journal-entry').html("#{helpers.j out}");)
        end
      end
    end
  end

Perhaps the corresponding coffeescript part that is Turbolinks friendly and uses jQuery for sending Ajax is akin to

$(document).on 'change', '#something', (e) ->
  $.get
    url: "/path/to/your/controller/#{e.target.value}.js"

you could send @journal object then use fields_for @journal into partial

.js.erb

$('.journal-entry').html("<%= j render partial: 'journal_entry_transaction_fields', object: @journal %>");

Partial .html.erb

<%= fields_for @journal do |f| %>
   ... code .....
<% end %>
Related