views:

29

answers:

1

I'm sure there's an easy solution for this but I'm new to Rails and need help with syntax.

In my controller I have:

@products = Product.all
format.json { render :json => @products }

And it works fine, returning data with the default column names used in the DB:

"product": {
  "created_at": "2010-10-08T17:24:27Z",
  "id": 24,
  "product_date": "2010-08-08",
  "product_name": "Product One",
  "updated_at": "2010-10-08T17:36:00Z"
}

What I need is something like:

"product": {
  "created_at": "2010-10-08T17:24:27Z",
  "id": 24,
  "start": "2010-08-08",
  "title": "Product One",
  "updated_at": "2010-10-08T17:36:00Z"
}

That is, changing product_date to start and product_name to title, but only in the JSON output.

It seems like an easy problem to solve but I'm not sure how to express it in Ruby/Rails syntax, so I would really appreciate any help. I cannot rename the database columns.

A: 

If you want to alter the JSON output for all Products, everywhere and all the time, simply override the to_json method on your Product model.

Here's the simple way to do that (in your Product class definition):

def to_json
  ActiveSupport::JSON.encode({
    :created_at => created_at
    :id => id
    :start => product_date
    :title => product_name
    :updated_at => updated_at
  })
end

You could get fancier and plug in a custom Serializer, but this should suffice for your purposes. One drawback of doing this so explicitly is that if your schema changes, this will have to be updated. This will also break the options usually available to the to_json method (:include, :only, etc) so, maybe it's not too hot.

jason
I knew it'd be easy, just didn't know how to go about it. Thanks Jason. Just out of curiosity, how would you go about it if you don't want to alter the JSON output application-wide? I'm mainly interested in the syntax difference between the two situations.
pthesis
Hmm, a simple way would be to just build a new hash to pass to `render`.
jason
I'm getting a "wrong number of arguments" error trying to access the JSON data with the above method in my model. Any thoughts?
pthesis
Maybe you can show me how to do it the hash way you suggested?
pthesis