13
9

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 5 years have passed since last update.

Rails よく使うクエリはmodelの中にscopeを書こう

Last updated at Posted at 2017-03-04

対象者

  • Controller、Viewの中にクエリが増えすぎて見づらくなってきた人
  • 同じようなクエリを色んな所で書いててDRYじゃないんじゃないかと感じる人

#問題

  • 複雑なクエリがController、Viewにあると可読性が悪くなる
  • 別のControllerに同じクエリを書く必要がある

##問題のController

sample_controller.rb

def index
  @arrival_books = Article.where(category_name: "book",
                                 created_at: 1.weeks.ago..Time.now)
  @tokyo_user = User.where(area: "tokyo", status: 0)
end

こんな感じのクエリが増えてくととても使いづらい。
よく使うクエリはモデルにscopeを使って切り出すと良い。

#modelにスコープを書くとこう↓

models/article.rb

scope :arrival_books, -> do
    where(category_name: book,
          created_at: 1.weeks.ago..Time.now)
end
models/user.rb
scope :tokyo_users, -> {where(area: "tokyo", status: 0)}

#結果
↓こんな風に呼べるようになりました!

sample_controller.rb
def index
  @arrival_books = Article.arrival_books
  @tokyo_users   = User.tokyo_users
end

クエリが複雑になればなるほど使いやすくなるので使ってみてください

#ちなみに、where区を追加することもできる

hoge_arrival_books = Article.where(user_id: "hoge").arrival_books

#値を渡すこともできる

sample_user = User.first
Article.ariival_books(sample_user)
article.rb
#sample_userを使ってクエリの条件を書ける
scope : arrival_books, ->(sample_user) do
    where(category_name: book,
          created_at: 1.weeks.ago..Time.now,
          user_id: sample_user.id)
end
13
9
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
13
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?