You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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!

修改 Pages Controller(pages_controller.rb)

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 of LIKE
  • For MySQL/SQLite: Use "LOWER(item_name) LIKE LOWER(?)"
修改视图文件(home.html.erb)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:04:19