2017-07-31 67 views
-1

我想仅渲染first_name场的前三个字母和email场的最后三个字母在Nominee模型JSON:如何在rails中仅渲染字段的一部分作为json?

def list 
    render json: Nominee.all, only: [:id, :first_name, :email, :phone,] 
    end 

哪里Nominee.all是客户的数组,first_nameemailphone是Nominee模型中string类型的字段。

我该怎么做?

+1

[active_model_serializers](https://github.com/rails-api/active_model_serializers)似乎很适合这里。 –

+0

出于好奇,你为什么要这样做? – 0112

回答

0

添加一种用于电子邮件的最后三个字母给你的模型:

class Nominee < ActiveRecord::Base # Or ApplicationRecord 
    def last_three_of_email 
    ... 
    end 
end 

使用to_json:methods选项:

nominee.to_json(
    only: [:id, :first_name, :email, :phone], 
    methods: [:last_three_of_email] 
) 

送回所需的JSON到客户端:

render json: Nominee.all.to_json(...) 

如果这变得更复杂,那么我建议你查看序列化程序(请参阅Sergio Tulentsev的评论)或JBuilder来呈现自定义的JSON。