LoginSignup
2
2

More than 5 years have passed since last update.

【Rails】一つの検索フォームで子モデルも一緒に検索できるようにする方法

Posted at

検索フォームの実装方法

検索フォームの実装方法は下記を参考にすれば、比較的簡単にできます。

railsで検索フォームを作ろう!!
Ruby on Rails 検索機能拡張 (railsチュートリアル)
【開発メモ】Railsアプリに検索機能を実装する方法をわかりやすくまとめてみた。
【Rails】1つの検索フォームで複数カラムをまたいで検索する方法

ここからが本題

includesで関連するテーブルをまとめて取得し、referencesで親子関係をきちんと明記することがポイントです。

親モデル名.includes(:子モデル名).where(['検索したいカラム名 LIKE ? OR 検索したいカラム名 LIKE ? ', "%#{search}%", "%#{search}%"]).references(:子モデル名)

includesに関するリファレンス
referencesに関するリファレンス

2
2
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
2
2