I was wondering if there is any way to just skip attributes having nil
values when to_json on ActiveRecord.
The default behavior is to include a nil value.
Is there an option way to make this value just not appear?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
@lars’s answer will work for a single object, but for an array of Active Record objects, you will have to iterate through every element of the array and do the conversion. If you want this conversion everytime you call
.to_jsonorrender :json =>for that model, you can override theas_jsonfunction in the model like this:Also, I am assuming you have defined,
ActiveRecord::Base.include_root_in_json = falsein the your environment(config/initializers/active_record.rbin Rails 3 andconfig/initializers/new_rails_defaults.rbin Rails 2). Otherwise, you will have to implement @lars’s function fully in the model(takingvalue[0]to get the attribute hash etc.).Use this method only if you want to do this everytime you call
.to_jsonorrender :json =>for that model. Otherwise you should stick to @lars’s answer.