[英]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. 在我的用户模型中,我有一个display_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: 我试图让我的控制器像这样返回display_name:
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? 问题是,控制器仅发送ID和电子邮件,而不发送display_name。我在做什么错?
According to the docs : 根据文档 :
To include the result of some method calls on the model use :methods:
要在模型上包含某些方法调用的结果,请使用: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.
选项include_root_in_json控制as_json的顶级行为。 If true, as_json will emit a single root node named after the object's type.
如果为true,则as_json将发出一个以对象类型命名的根节点。 The default value for include_root_in_json option is false.
include_root_in_json选项的默认值为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:
也可以通过将:root选项设置为true来实现此行为,如下所示:
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 或者有一个序列化器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.