Ruby on rails 如何将哈希键映射到封装的Ruby类(无表模型)的方法?
我正在使用RubyonRails 3,我正在尝试将哈希(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
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