我只想将Nominee
模型中first_name
字段的前三个字母和email
字段的最后三个字母渲染为 json:
def list
render json: Nominee.all, only: [:id, :first_name, :email, :phone,]
end
其中Nominee.all
是客户数组,first_name
、email
和phone
是被提名模型中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。