1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Ruby on Rails】Scopeに変数を渡す。

Last updated at Posted at 2020-09-30

業務でscopeについて少し戸惑ってしまったので、備忘録としてここにまとめておきます。
ちなみに書いている人間は、エンジニア歴1ヶ月の人間です。
間違っている点などあれば、コメントお願いいたします。

やりたかったこと

each分の変数をscopeに渡したい。

## 実際のコード

Office.rb
  scope :search, lambda { |keyword|
                   where('name LIKE (?) OR
                          address LIKE (?) OR
                          near_station LIKE (?) OR
                          introduction LIKE (?) OR
                          company LIKE (?)',
                          "%#{keyword}%",
                          "%#{keyword}%",
                          "%#{keyword}%",
                          "%#{keyword}%",
                          "%#{keyword}%")
                        }
offices_controller.rb
      keywords = params[:keyword].split(/[[:blank:]]+/).select(&:present?)
      offices_list = []
      keywords.each do |keyword|
        offices_list += Office.search(keyword)

コードは一部だけ抜粋していますが、このような形で実装することができました。
最終的には、上記のコードになりましたが下記のコードでも正常に動作はしました。

Office.rb
  scope :search, keyword { where('name LIKE (?) OR
                          address LIKE (?) OR
                          near_station LIKE (?) OR
                          introduction LIKE (?) OR
                          company LIKE (?)',
                          "%#{keyword}%",
                          "%#{keyword}%",
                          "%#{keyword}%",
                          "%#{keyword}%",
                          "%#{keyword}%")
                        }
1
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?