0
0

More than 3 years have passed since last update.

[Rails]1対多対1の孫モデルのidsを取って来るには

Last updated at Posted at 2020-06-15

(自分用)

TL; DR

pluckを使う

モデル構造

Userモデル

app/models/user.rb
class User < ApplicationRecord
  has_many :follow, class_name: 'Friendship', foreign_key: 'follow_id'
  has_many :followee, class_name: 'Friendship', foreign_key: 'followee_id'

Friendshipモデル

app/models/friendship.rb
class Friendship < ApplicationRecord
  belongs_to :follow, class_name: 'Account', foreign_key: 'follow_id'
  belongs_to :followee, class_name: 'Account', foreign_key: 'followee_id'

UserがFriendshipとのAssociationを1つ持つ。
FriendshipモデルがUserとのAssociationを2つ持つ。
1対多対1の関係。

each doは汚い

Deviseでユーザを作っているとして

app/controllers/users_controller.rb
~~
  def list
    ids = []
    current_user.follow.each do |f|
      ids << f.followee_id
    end
    @users = User.where(:id => ids)
  end
~~

5行も使ってしまった。

結論: 1行でも取ってこれるよ

app/controllers/users_controller.rb
~~
  def list
    @users = User.where(:id => current_user.follow.pluck(:followee_id))
  end
~~

以上です。

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