Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何将哈希键映射到封装的Ruby类(无表模型)的方法?_Ruby On Rails_Ruby_Ruby On Rails 3_Class_Hash - Fatal编程技术网

Ruby on rails 如何将哈希键映射到封装的Ruby类(无表模型)的方法?

Ruby on rails 如何将哈希键映射到封装的Ruby类(无表模型)的方法?,ruby-on-rails,ruby,ruby-on-rails-3,class,hash,Ruby On Rails,Ruby,Ruby On Rails 3,Class,Hash,我正在使用RubyonRails 3,我正在尝试将哈希(key,value对)映射到一个封装的Ruby类(无表模型),使哈希key作为一个类方法返回值 在我的模型文件中 class Users::Account #< ActiveRecord::Base def initialize(attributes = {}) @id = attributes[:id] @firstname = attributes[:firstname] @lastnam

我正在使用RubyonRails 3,我正在尝试将哈希(
key
value
对)映射到一个封装的Ruby类(无表模型),使哈希
key
作为一个类方法返回

在我的模型文件中

class Users::Account #< ActiveRecord::Base
  def initialize(attributes = {})
    @id        = attributes[:id]
    @firstname = attributes[:firstname]
    @lastname  = attributes[:lastname]
  end
end

def self.to_model(account)
  JSON.parse(account)
end
我可以

account = Users::Account.to_model(hash)
返回的(调试)

这很有效,但如果我这样做了

account.id
我得到这个错误

NoMethodError in Users/accountsController#new    
undefined method `id' for #<Hash:0x00000104cda410>
Users/accountscocontroller中的NoMethodError#new
未定义的方法“id”#
我想是因为
是一个散列(!)而不是类本身。另外,我认为使用
account=Users::account.to_model(hash)
不是正确的方法


怎么了?如何将这些散列键“映射”到类方法?

您尚未使用散列初始化类。你应该做:

json = "{\"id\":2,\"firstname\":\"Name_test\",\"lastname\":\"Surname_test\"}"
hash = Users::Account.to_model(json)
account = Users::Account.new(hash)

然后,
account.id
将给出值。

如果您像这样重写它,看起来会更好

account = Users::Account.from_json(json)
下面呢

def self.from_json(json_str)
   new(JSON.parse(json_str))
end
还有一个“块初始值设定项”,我经常使用它从散列初始化 因此,如果要使用它,可以将类定义转换为

class Users::Account
  include BlockInit
  attr_accessor :id, :firstname, :lastname
  def self.from_json(json_str)
    new(JSON.parse(json_str))
  end
end
def self.from_json(json_str)
   new(JSON.parse(json_str))
end
class Users::Account
  include BlockInit
  attr_accessor :id, :firstname, :lastname
  def self.from_json(json_str)
    new(JSON.parse(json_str))
  end
end