なんとなく日々徒然と

has_manyなassociationにメソッド追加

めっちゃ簡単に出来るんですね。
全然知らなかった。

http://stackoverflow.com/questions/10418193/how-to-add-methods-to-a-has-many-collection

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Customer < ActiveRecord::Base
  belongs_to :store
end

class Store < ActiveRecord::Base
  has_many :customers do
    def names
      self.map(&:name)
    end
  end
end
1
2
rails console
Store.last.customers.names # => customersの名前の配列が取れる!