Better way to return validation errors for nested models as json in Rails?
Updated to have the same format as Rails nested params
render json: { order: { entries: @order.entries.enum_for(:each_with_index).collect{|entry, index| { index => { id: entry.id, errors: entry.errors.to_hash, members: entry.members.enum_for(:each_with_index).collect{|member, index| { index => { id: member.id, errors: member.errors.to_hash } } unless member.valid? }.compact } } unless entry.valid? }.compact }}
You should get a JSON response like:
{ order: { entries: [ 0: { id: 1, # nil, if new record errors: {}, members: [ 0: { id: 7, # nil, if new record errors: { title: ["cant be blank"] } }, 1: { id: 13, # nil, if new record errors: { title: ["cant be blank"] } } ] } ] }}
P.S. Maybe others know a rails-integrated way of doing this. Otherwise, I would say this might be a good feature request for Rails in git.