【问题标题】:Complex attribute using ActiveResource in Rails 3.2.12在 Rails 3.2.12 中使用 ActiveResource 的复杂属性
【发布时间】:2013-03-11 23:52:11
【问题描述】:

我正在尝试将 Web 服务响应转换为我的 Rails 应用程序中的对象,我收到以下 json:

{
    "id": 1,
    "status": true,
    "password": "123",
    "userType": {
        "description": "description",
        "userTypeId": 1
    },
    "email": "abc@gmail.com"
}

我想像这样在 UserType Ruby 类中转换 userType 属性:

class UserType
  attr_accessor :userTypeId, :description
end

我使用 ActiveResource 与 webservice 通信,我尝试使用属性方法将 userType json 属性转换为 UserType 类,但属性方法不接受复杂类型,只接受字符串、整数等...

如何将 userType(webservice 响应)转换为 UserType Ruby 类?

Rails 3.2.12 和 Ruby 1.9.3p194

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activeresource


    【解决方案1】:

    您应该能够将userType 实现为实例方法。

    class MyResource < ActiveResource::Base
      self.site = "http://api.example.com/"
    
      def userType
        UserType.new(userTypeId: super.userTypeId, description: super.description) 
      end
    end
    

    这是有效的,因为 ActiveResource 会自动为您传递给类构造函数的属性散列中的每个键创建一个“getter”方法。当被调用的属性方法对应一个hash值时,ActiveResource返回一个自动生成的类MyResource::UserType的实例,分别响应userTypeIddescription方法。您可以通过在被覆盖的方法中调用 super 来获取此实例,并将 userTypeIddescription 的值传递给您自己的类。

    编辑: - 更正了类名

    PS:查看ActiveResource#load 方法以了解有关如何生成属性 getter 方法的更多详细信息。

    【讨论】:

    • 太棒了@And!您的解决方案有效,现在我可以使用 UserType 类。我看到您使用 ActiveSupport 而不是 ActiveResource,我应该使用哪个?他们之间有什么区别?我尝试使用 ActiveSupport,但收到错误消息。感谢您的帮助 =) !!
    • 糟糕.. 那里有一个错字。它实际上是 ActiveResource。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多