在我的用户模型中,我有一个方法display_name来输出用户的全名。
user.rb (id, first_name, last_name, email, ...)
def display_name
[first_name, last_name].compact.join(' ')
end
我试图让我的控制器像这样返回display_name:
def show
json_response({
user: user.as_json(only: [:id, :display_name, :email])
})
end
问题是,控制器只发送id和email,而不是display_name ..我做错了什么?
答案 0 :(得分:3)
根据docs:
要在模型上包含一些方法调用的结果,请使用:methods:
user.as_json(methods: :permalink)
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
# "created_at" => "2006/08/01", "awesome" => true,
# "permalink" => "1-konata-izumi" }
另外:
include_root_in_json选项控制as_json的顶级行为。如果为true,as_json将发出以对象类型命名的单个根节点。 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 } }
也可以通过将: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 } }
所以,可能有以下几点:
user.as_json(only: [:id, :email], methods: :display_name, root: true)
答案 1 :(得分:1)
你可以这样做:
user.as_json(only: [:id, :email], methods: [:display_name])
或
user.as_json(only: [:id, :email]).merge({'display_name': user.display_name})
或者有一个序列化器