Home Prevent has_many lookup during json serialization
Reply: 0

Prevent has_many lookup during json serialization

Manuel Trümper
1#
Manuel Trümper Published in 2017-09-13 23:43:32Z

I have a query like this

@templates = Template.find_by_sql("SELECT templates.*, jsonb_agg(fields.*) as fields FROM templates LEFT JOIN fields ON templates.id = fields.template_id GROUP BY templates.id ")

Inside the Model i defined a has_many relationship

has_many :fields, dependent: :destroy

inside my controller i render the result with

render json: @templates

The Resulting json is formatted as expected but rails always does additional unnecessary queries:

Template Load (0.6ms)  SELECT templates.*, jsonb_agg(fields.*) as fields FROM templates LEFT JOIN fields ON templates.id = fields.template_id GROUP BY templates.id 
rails_1  |   Field Load (0.3ms)  SELECT "fields".* FROM "fields" WHERE "fields"."template_id" = $1  [["template_id", 1]]
rails_1  |   Field Load (0.4ms)  SELECT "fields".* FROM "fields" WHERE "fields"."template_id" = $1  [["template_id", 2]]
rails_1  |   Field Load (0.3ms)  SELECT "fields".* FROM "fields" WHERE "fields"."template_id" = $1  [["template_id", 3]]

When i change the column name inside the query for example:

@templates = Template.find_by_sql("SELECT templates.*, jsonb_agg(fields.*) as fields_sql FROM templates LEFT JOIN fields ON templates.id = fields.template_id GROUP BY templates.id ")

No additional queries are performed but i end up with and unwanted key in my json (fields_sql instead of fields)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.46522 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO