2
1

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でhas_manyなmodelを条件付きで取ってくるのをあらかじめ定義しておくと読みやすい

Last updated at Posted at 2019-06-07

近況
転職してRailsマンに戻りました。(しばらくpythonおじさんだった)

やりたいこと

has_manyしているテーブルをselectするとき、コントローラの中でfindとか書かずに予めmodelの中に定義しておきたい。
(見た目スッキリさせたいとか、変数当てる必要がないから定義済みにしといた方が安全とか色々理由はあると思う)

どう書く?

lambdaを使うのが良いみたい。

app/models/user.rb
class User < ApplicationRecord
    # Userに紐づく予定を記録したSchedulesテーブルがあり、そこから稼働日に該当する予定だけを抜き出したい
    has_many :work_day, lambda { where not_work_day: True }, class_name: Schedules.name
end

コントローラからはこんな感じで書く。

app/controlers/user_controller.rb
def work_day
    @result = User.find(id).includes(:work_day)
end

参考: https://blog.falconsrv.net/articles/415

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?