开发者

Rails 2.3.8: how to parse JSON with field names other than DB columns

开发者 https://www.devze.com 2023-01-19 04:08 出处:网络
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:

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消