简体   繁体   中英

How to use as_json in a controller to return a model's method display_name?

In my user model, I have a method display_name to output the user's full name.

user.rb (id, first_name, last_name, email, ...)
  def display_name
    [first_name, last_name].compact.join(' ')
  end

I'm trying to get my controller to return display_name like so:

  def show
    json_response({
      user: user.as_json(only: [:id, :display_name, :email])
    })
  end

Problem is, the controller is only sending id and email, not display_name.. What am I doing wrong?

According to the docs :

To include the result of some method calls on the model use :methods:

user.as_json(methods: :permalink)
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006/08/01", "awesome" => true,
#      "permalink" => "1-konata-izumi" }

Also:

The option include_root_in_json controls the top-level behavior of as_json. If true, as_json will emit a single root node named after the object's type. The default value for include_root_in_json option is false.

user = User.find(1)
user.as_json
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#     "created_at" => "2006/08/01", "awesome" => true}

ActiveRecord::Base.include_root_in_json = true

user.as_json
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#                  "created_at" => "2006/08/01", "awesome" => true } }

This behavior can also be achieved by setting the :root option to true as in:

user = User.find(1)
user.as_json(root: true)
# => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#                  "created_at" => "2006/08/01", "awesome" => true } }

So, probably something along the lines of:

user.as_json(only: [:id, :email], methods: :display_name, root: true)

You can do:

user.as_json(only: [:id, :email], methods: [:display_name])

or

user.as_json(only: [:id, :email]).merge({'display_name': user.display_name})

Or have a serializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM