【问题标题】:globalize2 with xml/json support支持 xml/json 的 globalize2
【发布时间】:2011-01-07 16:35:51
【问题描述】:

我正在目标 c (iPhone) 中实现一个分布式应用程序、带有 Rails 的服务器和移动客户端。为了启用国际化,我使用了 joshmh 的 rails 插件“globalize2”。

然而,事实证明,当在 ActiveRecord 上调用 to_xml 或 to_json 时,此插件不会转换属性。有谁知道解决方法/补丁?你有什么想法可以解决这个问题,在哪里改变 globalize2?

使用: 导轨 2.3.5 globalize2:从 2010-01-11 提交

【问题讨论】:

    标签: ruby-on-rails xml json globalize2


    【解决方案1】:

    使用 Globalize2(以及 model_translations),模型中的翻译属性不是真正的属性,而是一种方法。因此,当您执行 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
    

    在这里,我只想在 json 响应中接收帖子 ID 和标题。有关更多信息,请参阅Rails API 中的 to_json(序列化)。

    【讨论】:

      【解决方案2】:

      我在 github 上找到了这个 fork:http://github.com/leword/globalize2 但它看起来像是基于旧版本。

      我自己也在寻找这个,但使用 :methods 选项解决了我的问题:

      如果你想翻译@item中的一个属性,你可以使用:

      class Item < ActiveRecord::Base
        translates :name
        def t_name
          self.name
        end
      end
      

      在你的控制器中:

      render :text => @item.to_xml(:methods => [ :t_name ])
      

      如果您的 api 路径类似于 /en/api/item.xml,您应该在 t_name 属性中获得英文翻译

      对于belongs_to 关系:

      belongs_to :category
      def category_name
        self.category.name
      end
      

      在你的控制器中:

      render :text => @item.to_xml(:methods => [ :category_name ])
      

      您的用例可能不同。以上是适合我的解决方法。

      【讨论】:

        猜你喜欢
        • 2011-06-09
        • 1970-01-01
        • 1970-01-01
        • 2013-06-03
        • 1970-01-01
        • 2016-02-13
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        相关资源
        最近更新 更多