rails:検索時にリテラルのselect句やjoin句を使う

一般的だと思うけど、覚書。

controllerではモデルのリテラルを指定して検索。

controller/tallent_controller.rb

class TallentController  < ApplicationController
  def index
    @tallents = Tallent.select(Tallent::SELECT_STR)
      .joins(Tallent::JOIN_STR)
      .order(name: 'asc')
  end
end

モデル側に、select句やjoin句のリテラルを定義しておく。 (記述する場所はモデルでなくてもよい)

model/tallent.rb

class Tallent < ApplicationRecord
  SELECT_STR = "
    tallents.id AS tallent_id,
    tallents.name AS tallent_name,
    pirates_corps.name AS pirates_corps_name
  "
  JOIN_STR = "
    LEFT OUTER JOIN
      pirates_corps
    ON
      tallents.pirate_corp_id = pirates_corps.id
  "
end