LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】アソシエーション先での検索方法

Posted at

Railsに触れて3ヶ月、忘れないようにメモしときます。

環境

ruby 2.6.3
Rails 6.0.1

前提

Authorモデル has_many Bookモデル

Bookモデル has_many Chapterモデル

アソシエーション先で検索

例) title という名前の本( Book )を書いた人( Author )を検索

matched_authors = Author.includes(:books).where(books: { name :title })

アソシエーション先でキーワード検索

例) keyword という言葉を含む名前の本( Book )を書いた人( Author )を検索

matched_authors = Author.includes(:books).where('books.name LIKE ?', "%#{keyword}%")

where句の第1引数のSQL文の ? を 第2引数で置き換えて検索してくれます。

書き方いろいろあると思います。

もっと良い方法があればコメントで教えていただけると嬉しいです。


他にも where の使い方 参考先


ちなみに...

アソシエーションリレーション、似ていますが

アソシエーション ⇒ モデルの関係性

リレーション ⇒ DBテーブルの関係性

を言うみたいです。

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