This project is archived and is in readonly mode.

#5254 ✓resolved
Alex Le

Rails 3RC's ActiveModel#as_json outputs array of message instead of hash of columns and messages

Reported by Alex Le | July 30th, 2010 @ 07:47 PM | in 3.0.2

This change broke a bunch of my JavaScript code to handle validation on the client side (works perfectly fine on Rails 3B4 but not on Rails 3RC)

To replicate this issue:

Declare a model, say "Expense" with "amount" as a required field:

class Expense < ActiveRecord::Base
  validates_numericality_of :amount
end

In the console,

expense = Expense.new
expense.errors.to_json
=>  "[\"Account is not a number\"]"

Basically there's no way that I can get back the column which the error occurs to handle it on the front-end. In Rails 3 beta 4, it used to return this result, and it's the preferred result as well:

expense.errors.as_json  # I tried to_json and it gave me a stack level too deep
=> { :amount => "is not a number }

For me, I have this snippet in the view code to hook up to my custom JavaScript validations:

var expense = <%= raw expense.to_json(:methods => [:errors]) %>;
// handling errors for the expense depends on the columns in expense.expense.errors

I'd get back the errors as a json object and I can iterate thru the columns attributes to handle the errors, however, this is no longer the case with Rails 3RC.

I checked the log and I think this commit broke the expected behavior : 7bd85a8fc2d216a5e2b1 (http://github.com/rails/rails/commit/7bd85a8fc2d216a5e2b1d0380df572...)

Can you please switch this back to how Rails 3b4 handles the serialization of the errors array? If the user wants to have the full error messages, then they can call another methods like expense.to_json(:methods => [:error_messages]) and this would get them the full error messages.

Thanks,

Alex

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Attachments

Referenced by

Pages