Ruby on Rails新手求助:将地址搜索改为item_name搜索
Hey there! Since you're new to Ruby on Rails, let's walk through how to switch your search functionality from targeting an address field to the item_name field. We'll cover both the controller and view files you mentioned—super straightforward once you see it!
First, let's update the logic in your controller to look for matches on the item_name field instead of address. Here's what the modified home action might look like:
# app/controllers/pages_controller.rb class PagesController < ApplicationController def home if params[:search].present? # Replace the address field reference with item_name @items = Item.where("item_name LIKE ?", "%#{params[:search]}%") else @items = Item.all # Keep your existing default logic here if different end end end
A quick tip for better usability: If you want case-insensitive search (so "Apple" matches "apple"), adjust the query based on your database:
- For PostgreSQL: Use
item_name ILIKE ?instead ofLIKE - For MySQL/SQLite: Use
"LOWER(item_name) LIKE LOWER(?)"
Next, update your search form to reflect that we're searching by item name instead of address. This helps users understand what to input, and makes sure your result display shows the right field:
<!-- app/views/pages/home.html.erb --> <div class="search-container"> <%= form_tag home_path, method: :get do %> <%= label_tag :search, "Search Items by Name:" %> <%= text_field_tag :search, params[:search], placeholder: "Type an item name..." %> <%= submit_tag "Search" %> <% end %> </div> <!-- Display search results (adjust this to match your existing layout) --> <% if @items.present? %> <h3>Matching Items</h3> <div class="results-list"> <% @items.each do |item| %> <div class="item-card"> <h4><%= item.item_name %></h4> <!-- Add other item details here as needed --> </div> <% end %> </div> <% end %>
Quick Check
After making these changes, restart your Rails server (if it's running) and test it out! Try searching for an item name you know exists in your database—you should see the matching results populate correctly.
内容的提问来源于stack exchange,提问作者Amer Bearat

