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

別名の外部キーで紐付けたテーブルを結合する

Last updated at Posted at 2021-08-09

調べてもぱっとわかる情報が見つからなかったので備忘録用に。

例えば

user.rb
has_many :own_groups, 
         class_name: "Group",
         foreign_key: "owner_id",
         dependent: :destroy
groups.rb
belongs_to :owner, class_name: "User"

というのがあったとする。

コード

しかしjoinsするだけだとuserの情報を返してくれないのでselectする

groups.rb
scope :with_owners_info, -> () do
    <query>
    .joins(:owner)
    .select("
        groups.id,
        groups.name,
        groups.desc,
        groups.updated_at,
        users.id AS owner_id,
        users.name AS owner_name,
    ")
end

最後に.to_jsonなり.to_aなりする。

0
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
0
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?