简体   繁体   中英

Rails: loading partial with jQuery

I wanna show the search results dynamically by requesting the action which returns a javascript, which loads the partial. I have done some reading and escape_javascript seems like a right way to do it. But nothing shows up and I get 500 internal server error.

Here is some code

in controller:

 def search
    @user = User.find_by email: params[:email]

    respond_to do |format|
      if @user && @user.user_type_type == "Employee"
        format.js
      else
        format.js {render "failed_search"}
      end
    end
  end

view with the search form:

<div id="search-employee">
  <%= form_tag({controller: "employees", action: "search"}, method: :get, remote: true) do %>
      <%= label_tag 'email', "Search for:" %>
      <%= text_field_tag 'email'%>
      <%= submit_tag("Search") %>
  <% end %>

  <div id="search-result" class="row">
  </div>
</div>

js returned by the action (works when I put plain text to html instead of escaping js)

$('#search-result').html("<%= escape_javascript(render :partial => 'employees/search_result') %>");

I would show you the partial, but it does not get rendered even when I put plain text there, so it is not that.

Here is the output from the console, indeed it looks informative, I must have missed it.

Completed 500 Internal Server Error in 10ms (ActiveRecord: 0.2ms)

ActionView::Template::Error (Missing partial employees/_search_result.html.erb with {:locale=>[:en], :formats=>[:js, :html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/home/johnny/Desktop/ror/pub_crawler/pub_crawler_1.2/app/views"
  * "/home/johnny/.rvm/gems/ruby-2.2.1@rails4.2/gems/devise-3.5.6/app/views"
):
    1: //does not work
    2: $('#search-result').html("<%= escape_javascript(render :partial => 'employees/search_result.html.erb') %>");
    3: 
    4: $('#search-result').html('<div class="col-3-md"><%= @user.user_type.name %></div> <div class="col-3-md"><%= @user.user_type.surname %></div> <div class="col-3-md"></div>');
  app/views/employees/search.js.erb:2:in `_app_views_employees_search_js_erb__3438283462284537863_70351967525560'
  app/controllers/employees_controller.rb:12:in `search'

EDIT: ok, I'm a moron, It was a typo in file name...

Could you post the output from your rails console and the search_result partial? I suspect that Rails either can't find your partial file, or the partial is trying to use a variable that is undefined.

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