如何在轨道中仅将字段的子字符串呈现为 json?



我只想将Nominee模型中first_name字段的前三个字母和email字段的最后三个字母渲染为 json:

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

其中Nominee.all是客户数组,first_nameemailphone是被提名模型中string类型的字段。

我该怎么做?

为电子邮件的最后三个字母添加一个方法到模型:

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。

最新更新