[英]globalize2 with xml/json support
I'm implementing a distributed application, server with rails and mobile clients in objective c (iPhone). 我正在目标c(iPhone)中实现分布式应用程序,具有rails的服务器和移动客户端。 To enable internationalization, I use the rails plugin 'globalize2' by joshmh. 为了实现国际化,我使用了joshmh的rails插件“ globalize2”。
However, it turned out that this plugin does not translate attributes when calling to_xml or to_json on an ActiveRecord. 但是,事实证明,在ActiveRecord上调用to_xml或to_json时,此插件不会转换属性。 Does anyone know of a workaround / patch? 有谁知道解决方法/补丁? Do you have any ideas how to fix this, where to alter globalize2? 您是否有解决办法,在哪里更改globalize2有任何想法?
Using: Rails 2.3.5 globalize2: commit from 2010-01-11 使用:Rails 2.3.5 globalize2:从2010年1月11日提交
With Globalize2 (and with model_translations as well) translated attribute in a model is not a real attribute but is a method. 对于Globalize2(以及model_translations),模型中的转换属性不是真实属性,而是一种方法。 Thus and so when you execute to_json method you can use :methods , as Joris suggested, but in a simpler way: 这样,当执行to_json方法时,可以使用:methods ,如Joris所建议的那样,但是以一种更简单的方式:
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. 在这里,我只想接收json响应中的帖子ID和标题。 For additional information see to_json (Serialization) in Rails API . 有关更多信息,请参见Rails API中的 to_json(序列化)。
I found this fork on github: http://github.com/leword/globalize2 But it looks like it is based on an older version. 我在github上找到了这个fork: http : //github.com/leword/globalize2但看起来它是基于旧版本的。
I was looking for this myself, but solved my problem using the :methods option: 我自己在寻找这个,但是使用:methods选项解决了我的问题:
If you want to translate one attribute in @item, you can use: 如果要转换@item中的一个属性,可以使用:
class Item < ActiveRecord::Base
translates :name
def t_name
self.name
end
end
And in your controller: 在您的控制器中:
render :text => @item.to_xml(:methods => [ :t_name ])
If your api path is something like /en/api/item.xml, you should get the english translation in the t_name attribute 如果您的api路径类似于/en/api/item.xml,则应在t_name属性中获取英文翻译
For a belongs_to relation: 对于一个归属关系:
belongs_to :category
def category_name
self.category.name
end
And in your controller: 在您的控制器中:
render :text => @item.to_xml(:methods => [ :category_name ])
Your use case is probably different. 您的用例可能有所不同。 Above is a workaround that works for me. 以上是对我有用的解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.