Rails 4 form_tag update element with partial

2019-09-02 02:05发布

问题:

In Rails 4 how do I adjust the below controller, view and partial view such that when I click the "Update Time" Submit button, the html div with id of 'search_results' is updated with content generated by the _results.html.erb partial?

I have not used Rails in some time and I seem to remember it was extremely simple to do in Rails 1. The documentation I am finding for Rails 4 seems to involve JQuery which I am not familiar with and do not understand how to tie it into this form.

I have had a read through this: http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html

But still do not entirely understand what is going on.

RuleSearchController.rb

class RuleSearchController < ApplicationController
  def index

  end

  def results

  end
end

index.html.erb

<%= form_tag('/rule_search_results', :id => 'search_form') do %>
  <%= submit_tag "Update Time" %>
<% end %>

<div id='search_results'>
  <%= render partial: "results" %>
</div>

_results.html.erb

<%= Time.new %>

Update The current answer is doing some weird things. It works when I have something in _results.html.erb which is a simple one liner like:

<%= Time.new %>

If however I do something as simple as this:

<%= Time.new %>
<hr />

Whilst there is no error coming up on the console, nothing happens and the search results div is not updated.

Further Update I can iterate an array of AR objects and have their name print in the search_results div provided I do it in one like like below and that it is the only line in the file:

<% for rule in rules do %><%= rule.name %><% end %>

The below however does not work

<% for rule in rules do %>
  <%= rule.name %>
<% end %>

回答1:

This should work:

index.html.erb

<%= form_tag('/rule_search_results', :id => 'search_form', remote: true) do %>
  <%= submit_tag "Update Time" %>
<% end %>

Then create a file called 'results.js.erb' in the same directory as your _results.html.erb file with this:

$('#search_results').html('<%= render partial: "results" %>');

What this does is the remote: true tells the controller than it's a javascript request, and so the controller knows to look for the file with the method name followed by .js.erb and run the JS code automatically.

Update: In answer to the issues with multi-line HTML, you can add a 'j' before then render, and this will escape the output:

$('#search_results').html('<%= j render partial: "results" %>');