Rails 活动记录 - :包含仅包含特定字段



我正在研究一个简单的API。 我希望这个索引方法只返回 person 表中的两个或三个字段,而不是该表中的每个字段。

api :GET, "/v2/branches/", "Return every branch."
  def index
    @branches = Branch.includes(:people, :social_link).where("branches.company_id = ?", @company.id)
    render json: @branches.to_json(include: [:people, :social_link])
  end

与其归还每个人的第一个孩子,我只想让它向first_name展示,last_name,email_address...... 有什么想法吗?

因此,根据这篇博文,似乎一个可能的解决方案正在这样做

render json: @branches.to_json(
               include: {
                 people: { only: [:first_name, :last_name, :email]},
                 :social_link
               })

虽然,如果适合您的目的,我还建议为模型制作一个序列化程序。

最新更新