LoginSignup
1
2

More than 5 years have passed since last update.

モデルのメソッドを利用してjson化したい

Posted at

内部APIを作成しているときに、ふとモデルのメソッド実行したいなと。


class User < ApplicationRecord
  def name
    first_name + last_name
  end
end

こんな感じのメソッドがあったとして、nameをjsonで返したい!

簡単にできます。


User.all.limit(5).as_json(methods: [:name])

=begin

# 結果
 [
  {
    "id"   => 1,
    "name" => "テスト太郎",
    ~~
  },
  ~~
 ]

=end

すんなりできたので感動した!!

参考:
http://stackoverflow.com/questions/10821138/custom-model-method-that-should-be-included-in-json-serialization

1
2
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
1
2