Joshua
Joshua

Reputation: 694

Rails Active Record - :includes with only specific fields

I'm working on a simple API. I'd like this index method to return only two or three fields from the person table, rather than every field from that table.

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

Rather than returning each persons first born child, i'd just like it to show first_name, last_name, email_address... Any ideas?

Upvotes: 2

Views: 4163

Answers (1)

manu29.d
manu29.d

Reputation: 1568

So, according to this blog post, it seems a possible solution is doing this

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

Although, I would also suggest making a serializer for the model if that suits your purpose.

Upvotes: 3

Related Questions