Search code examples
ruby-on-railsxmljsonglobalize2

globalize2 with xml/json support


I'm implementing a distributed application, server with rails and mobile clients in objective c (iPhone). To enable internationalization, I use the rails plugin 'globalize2' by joshmh.

However, it turned out that this plugin does not translate attributes when calling to_xml or to_json on an ActiveRecord. Does anyone know of a workaround / patch? Do you have any ideas how to fix this, where to alter globalize2?

Using: Rails 2.3.5 globalize2: commit from 2010-01-11


Solution

  • With Globalize2 (and with model_translations as well) translated attribute in a model is not a real attribute but is a method. Thus and so when you execute to_json method you can use :methods, as Joris suggested, but in a simpler way:

    class Post < ActiveRecord::Base
      attr_accessible :title, :text
      translates :title, :text
    end
    
    class PostsController < ApplicationController
      def index   
        @posts = Post.all
        respond_to do |format|
            format.html
            format.json { render :json => { :posts => @posts.to_json(:only => :id, :methods => :title) }}
            format.js
        end
      end
    end
    

    Here I would like to receive only post id and title in json response. For additional information see to_json (Serialization) in Rails API.