LoginSignup
3
4

More than 5 years have passed since last update.

scopeの使い道

Posted at

scopeを使ったのでメモ。

なんでscope使うの?

.hoge.hogehogeのようにメソッドチェーンができるから。複雑な検索(.where(...)みたいな)がやりやすくなります。

今回やったことは?

2つのDBがあり、それらはhas_manyでリレーションしていて、whereするときに汎用的に使えるようにすること。
書いたコードはこんな感じ。

sample.rb
scope :item_is, -> id{ where(item_id: id) }
scope :my_item, -> item_is(1)
scope :your_item, -> item_is(2)
scope :his_item, -> item_is(3)
scope :hers_item, -> item_is(4)

1行目のitem_idが引数名となる。もし取ってくる値がitem_idではなく、違うものになったときは1行目のwhere(item_id: id)の()中だけ変更すれば2~3行目の検索内容を同時に変えることができ、汎用性が出る。

socpeにしたらうまくいかない?

私はscopeを書く前にいったん、whereで書いて任意の値が取れるかどうかを試してから書き換えました。この時scopeに書き換えると動かないという状況になりました。その原因はArrayクラスだったからでした。

Arrayクラス → whereは使えない。selectやmapなどで検索する
ActiveRecord → whereが使える。

というわけで、Arrayクラスとかに入れてしまったものに対してはwhere/scopeが使えないというわけ。今後もこれに引っ掛かりそうだ・・・

3
4
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
3
4