LoginSignup
1
0

More than 1 year has passed since last update.

二つのテーブルから検索する機能を実装しました。

Posted at

今回はarticlsテーブルとresolutionsテーブルから検索するコードを掲載します。

1.アソシエーションの状況
Image from Gyazo
2.ルーティングの設定

routes.rb
Rails.application.routes.draw do
  devise_for :users 
  root to: 'users#index'
  resources :resolutions 
    
  resources :articles
  resources :users do
    collection do
      get 'search'
    end
  end
end

3.コントローラーの記述

users_controller.rb
lass UsersController < ApplicationController

  def index
    @resolutions = Resolution.includes(:user).order('created_at DESC')
    @articles = Article.includes(:user).order('created_at DESC')
  end

  def show
    @user = User.find(params[:id])
    @resolutions = @user.resolutions.order('created_at DESC')
    @articles = @user.articles.order('created_at DESC')
  end

  def search
    @resolutions = Resolution.search(params[:keyword])
    @articles = Article.search(params[:keyword])
  end

end

4.モデルの記述

article.rb
class Article < ApplicationRecord
  validates :title,   presence: true
  validates :content, presence: true
  belongs_to :user

  def self.search(search)
    if search != ''
      Article.where('title LIKE(?)', "%#{search}%")
    else
      Article.all
    end
  end
end
resolution.rb
class Resolution < ApplicationRecord
  validates :erroe_message, presence: true
  validates :language, presence: true
  validates :status, presence: true
  validates :code, presence: true
  validates :cauce, presence: true
  belongs_to :user

  def self.search(search)
    if search != ''
      Resolution.where('erroe_message LIKE(?) OR status LIKE(?)', "%#{search}%", "%#{search}%")
    else
      Resolution.all
    end
  end
end

5.htmlの記述

  • トップ画面(検索画面がある画面)
users/index.html.erb
<%= form_with(url: search_users_path, local: true, method: :get, class: "search-form") do |form| %>
   <%= form.text_field :keyword, placeholder: "投稿を検索する", class: "search-input" %>
   <%= form.submit "検索", class: "search-btn" %>
<% end %>
  • 検索結果画面
users/serch.html.erb
<div class="contents row">
<div class="title-name">検索結果</div>
  <% @resolutions.each do |resolution| %>
    <%= render partial: "resolutions/resolution", locals: { resolution: resolution } %>
  <% end %>
   <% @articles.each do |article| %>
    <%= render partial: "articles/article", locals: { article: article } %>
  <% end %>
</div>

結論

今回はこのコードの記述でなんとか実装することができました。
どちらとも紐づいているuserを活用することでうまく実装できました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0