I had a hard time searching multiple tables by keyword in one form, so I will share it as a memorandum.
Parent table
recipes |
---|
id |
title |
Child table
ingredients |
---|
id |
name |
recipe_id(FK) |
ruby:views/recipes/search.html.erb
<%= form_with url: search_recipes_path, local: true, method: :get do |f| %>
<%= f.text_field :keyword, placeholder: "Enter a keyword" %>
<%= f.submit "Search" %>
<% end %>
The entered content is stored in: keyword and is received by the controller's params [: keyword].
routes.rb
resources :recipes do
collection do
get :search
end
end
This time it is nested in the recipe table routing.
recipes_controller.rb
def search
@recipes = Recipe.includes(:ingredients).references(:ingredients).search(params[:keyword])
end
Let the Recipe model include the ingredients table. If you use where after includes, you need references. Pass params to scope described in model by search method.
recipe.rb
class Recipe < ApplicationRecord
has_many :ingredients, dependent: :destroy
scope :search, -> (keyword) {
where('title like :q OR name like :q', q: "%#{keyword}%") if keyword.present?
}
end
params [: keyword] is passed as an argument to (keyword). If the keyword is empty, then @ recipes = Recipe.all.
ruby:views/recipes/search.html.erb
<%= form_with url: search_recipes_path, local: true, method: :get do |f| %>
<%= f.text_field :keyword, placeholder: "Enter a keyword" %>
<%= f.submit "Search" %>
<% end %>
<h1>search results</h1>
<% @recipes.each do |r| %>
<%= r.title %>
<% end %>
This is completed. If you want to add other columns to your keyword search, use OR to add the column name to where.
https://note.com/marikooota/n/nc7dc2868f178
How to search with multiple words ↓ https://qiita.com/tomaaaaaaaa/items/4c2beeb504da058408a4 https://qiita.com/Orangina1050/items/ca4e5dc26e0a32ee3137
Recommended Posts