I have a Rails 3.1 controller that renders a user’s contacts, including associated email objects and message objects. If I am only rendering the contacts, I can do the following:
@contacts = @current_user.contacts.order('last_name asc', :include => [:emails, :messages])
render json: @contacts, :include => [:emails, :messages]
As you can see, I want to sort the contacts by last name rather than the default id. I am now needing to render the user object with other associated objects as well. So I have tried the following, but of course the contacts are not in the appropriate order:
render :status => 200, :json => {
:user => @current_user.as_json(
:include => {
:foos => {
:except => :user_id
},
:contacts => {
:except => :user_id,
:include => [:emails,:messages]
},
:bars => {
:except => :user_id
}
}
)
}
I didn’t see any help in the as_json documentation, and I haven’t been able to find the right syntax by trial and error.
In this case I would order the contacts in Ruby / SQL and just build your own JSON to render instead of using as_json and its various
:include/:exceptmethods.Build a hash of your data and then send it along to render.
There are all sorts of libraries that can make building JSON easier. JBuilder is one such library. Look at the bottom of the JBuilder page for links to other similar libraries.