Rails 5.2应用中AJAX功能失效问题排查求助
Let's break down the issues preventing your AJAX search from working and fix them step by step:
1. Wrong Form Action Route
Your form uses a hardcoded 'search' action, but your route is defined as get 'welcome/search'—this means the form is submitting to the wrong URL. Use Rails' route helper to generate the correct path instead:
Modified welcome/index.html.erb:
<%= form_tag(welcome_search_path, method: :get, remote: true) do %> <%= label_tag(:q, "Search for:") %> <%= text_field_tag(:q) %> <%= submit_tag("Search") %> <% end %> <div id="results"> <%= render 'searchresults' %> </div>
Alternatively, you can simplify your route to get 'search', to: 'welcome#search' and use search_path in the form instead.
2. Mismatched Database Field in Query
In your WelcomeController#search method, you're querying for a name field, but your partial clearly uses article.title and article.description—your Article model likely doesn't have a name column. Fix the query to target the correct fields:
Modified WelcomeController:
class WelcomeController < ApplicationController def index @articles = Article.all end def search @query = params[:q] # Search both title and description (adjust based on your actual needs) @articles = Article.where('title LIKE ? OR description LIKE ?', "%#{@query}%", "%#{@query}%") respond_to do |format| format.html { redirect_to root_path, notice: "Search results loaded" } # Fixed redirect format.js end end end
3. Unescaped HTML in JavaScript Partial
Your search.js.erb is rendering the partial without escaping HTML, which will cause syntax errors in JavaScript (due to quotes and line breaks in the rendered HTML). Use Rails' j (short for escape_javascript) helper to safely escape the content:
Modified search.js.erb:
$('#results').html("<%= j render 'searchresults' %>")
4. Verify Rails UJS is Loaded
The remote: true attribute relies on Rails UJS to handle AJAX requests. Double-check that your app/assets/javascripts/application.js includes this line:
//= require rails-ujs
Also make sure your application layout (app/views/layouts/application.html.erb) includes the JavaScript tag:
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
5. Fix the Invalid Redirect in Controller
Your original format.html { redirect_to @articles } is invalid because @articles is an ActiveRecord collection, not a path. Replace it with a valid route (like the root path) for non-AJAX requests.
After applying these fixes, your AJAX search should work as expected—submitting the form will update the #results div without reloading the page.
内容的提问来源于stack exchange,提问作者D T

