2

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?

Joshua
  • 694
  • 1
  • 8
  • 19
  • Is this bigger than what it looks like? http://stackoverflow.com/questions/2572284/how-to-override-to-json-in-rails – manu29.d Jan 30 '15 at 07:06

1 Answers1

3

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.

manu29.d
  • 1,538
  • 1
  • 11
  • 15