LoginSignup
0
0

More than 5 years have passed since last update.

has_manyで関連づけられたクラスでメソッドを使う

Posted at

基本的なことかもしれないけど、知らなかったのでメモ

環境

ruby 2.3.0
rails 4.2.6

やり方

例として下記のようなModelがあり
Projectに所属するMemberの名前が配列で欲しいとする場合

class Project < ActiveRecord::Base
  has_many :members
end

class Member < ActiveRecord::Base
  def self.names
    # relationを使うとhas_manyで関連づけられたデータが取れる
    relation.map(&:name)
  end
end

すると下記のように取れる

@project.members.names

ただ、下記のようにするとrelationが無いのでエラーが発生する。

Member.names
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