简体   繁体   中英

Render Form partial from Ajax in rails

I have a form as image below:

部分表格

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:

文件 .js.erb

Adding :remote => true it makes the button asynchronously(Ajax call).

index.html.erb

<%= link_to "Add Journal", new_journal_path, remote: true, class: 'new_journal_button'%>

new.js.erb

$('.new_journal_button').after("<%= j render('form') %>");
$('.new_journal_button').hide();

If you want to submit a form asynchronously(Ajax call)

_form.html.erb

<%= form_for(@journal, remote: true) do |f| %>
  <div class="field">
    <%= f.label "journal" %><br>
    <%= f.text_field :title, placeholder: 'Journal', autofocus: true, 'data-behavior' => 'submit_on_enter' %>
  </div>
<% end %>

Journals_controller.rb

  def index
     @journal = Journal.new
     @journals = Journal.all
  end

  def create
    @journal = Journal.new(journal_params)
    respond_to do |format|
      if @journal.save
        format.html { redirect_to @journal, notice: 'Journal was successfully created.' }
        format.js
      else
        format.html { render :new }
      end
    end
  end

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM