Ordering JSON rendered by Rails controller

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.

Answers


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 / :except methods.

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.


Need Your Help

C#: windows application Caspol

c# windows caspol

I have a windows application.. which will run in a very restricted environment ... The windows app queries event logs and performance counters.. it requires these permission.. the log in account be...

How to Open Applet with JFrames on HTML page load

java swing file-upload jframe japplet

Im a newbie in Java. I have a java applet with JFrames on it. it is running on Tomcat. I want to open it on a load. I can run it using a button and the button will post on the servlet and the servlet

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.