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 1 year has passed since last update.

[Rails] 別モデルのscopeをくみあわせて新しいscopeをつくる

Posted at

環境

  • Rails6
  • mysql 5.7

やりたいこと

別モデルのscopeをくみあわせて新しいscopeをつくりたい。
たとえば、吹奏楽部でフルートパート1年の徴収済みの部費を集計したいとします。
(部費テーブルとメンバーテーブルは分かれてるとして、)

buhi_table.sum(:buhi).search_1nen_members('flute')

こうかけるscopeをつくりたい
その時、メンバーテーブルの既存スコープを組んでつくれると楽だよね。

やり方

メンバーテーブルのsearch_part、search_1nenというスコープを組みたいとします。

scope: :search_1nen_members, ->(part_name) do
  joins(:member).merge(Member.scope_part(part_name).scope_1nen) if part_name.present?
end

こう定義することで、

buhi_table.sum(:buhi).search_1nen_members('flute').to_sqlで下のSQLが確認できる :smiley:

SELECT sum(buhis.buhi) FROM buhis INNER JOIN `members` ON `members`.`id` = `buhis`.`member_id` WHERE  `members`.`gakunen` = 1 and `members`.`part` = `flute` "
1
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
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?