Performance: JSON rendering
This affects server response time and client load speed by controlling how JSON data is generated and sent.
render json: @users.as_json(only: [:id, :name], include: { posts: { only: [:id, :title] } })render json: @users.to_json(include: :posts, methods: :expensive_method)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Rendering large nested JSON with methods | N/A (server-side) | N/A | N/A | [X] Bad |
| Rendering limited JSON fields with includes | N/A (server-side) | N/A | N/A | [OK] Good |
render json: @user do in a Rails controller?render json: command in Rails sends data as JSON format to the client instead of rendering an HTML view.@user in this context@user sends the user object data as JSON in the HTTP response.json: @post, status: 201.def show @user = User.find(1) render json: @user.to_json(only: [:id, :name]) end
to_json(only: [:id, :name])id and name fields of the user object.id and name are included, so email is excluded.def index @users = User.all render json: @users only: [:id, :email] end
only option must be passed inside to_json or as a render json: option hash, not as a separate argument.only optionrender json: @users.to_json(only: [:id, :email]) or render json: @users, only: [:id, :email] inside a hash, but the given code passes only outside the hash.User.where(active: true) to get only active users.to_json(only: [:id, :name]) to include only those fields in the JSON output.only incorrectly. render json: User.where(active: true).only(:id, :name) uses a non-existent only method on ActiveRecord relation.Pass the test and this pattern moves unknown