Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/60.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 On Rails_Activerecord - Fatal编程技术网

Ruby on rails 访问散列中的属性

Ruby on rails 访问散列中的属性,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有以下课程: class Profile < ActiveRecord::Base serialize :data end 类配置文件

我有以下课程:

class Profile < ActiveRecord::Base
  serialize :data
end
类配置文件
配置文件有一个单独的列
data
,其中包含一个序列化哈希。我想在该散列中定义访问器,这样我就可以执行
profile.name
,而不是
profile.data['name']
。这在Rails中可能吗?

类配置文件class Profile < ActiveRecord::Base
  serialize :data # always a hash or nil

  def name
    data[:name] if data
  end
end
序列化:数据#始终为哈希或零 定义名称 数据[:名称]如果是数据 结束 结束
类配置文件
Ruby非常灵活,您的模型只是一个Ruby类。定义所需的“访问器”方法和所需的输出

class Profile < ActiveRecord::Base
  serialize :data

  def name
    data['name'] if data
  end
end
如果配置文件包含唯一信息,则可以使用
方法\u missing
尝试查找哈希

def method_missing(method, *args, &block)
  if data && data.has_key?(method)
    data[method]
  else
    super
  end
end

简单明了的方法:

class Profile < ActiveRecord::Base
  serialize :data

  def name
    self.data['name']
  end

  def some_other_attribute
    self.data['some_other_attribute']
  end
end
使用后一种方法,您只需定义
method\u missing
,然后调用
@profile
上的任何属性,该属性是
数据中的键。因此,调用
@profile.name
将通过
方法\u missing
并从
self.data['name']
中获取值。这将适用于
self.data
中存在的任何键。希望有帮助

进一步阅读:


我要回答我自己的问题。看起来ActiveRecord::Store就是我想要的:

因此,我的班级将成为:

class Profile < ActiveRecord::Base
  store :data, accessors: [:name], coder: JSON
end
类配置文件

我相信其他人的解决方案都很好,但这太干净了。

这应该可以做到:
def method\u missing(method,*args,&block);self[:data][method.to_s].presence | | super(method,*args,&block);结束
它是动态的,但测试
profile.response\u to?:名字
将是好东西,我不知道那个。我几乎和我了解脏模块时一样兴奋!
class Profile < ActiveRecord::Base
  serialize :data

  def name
    self.data['name']
  end

  def some_other_attribute
    self.data['some_other_attribute']
  end
end
class Profile < ActiveRecord::Base
  serialize :data

  def method_missing(attribute, *args, &block)
    return super unless self.data.key? attribute
    self.data.fetch(attribute)
  end

  # good practice to extend respond_to? when using method_missing
  def respond_to?(attribute, include_private = false)
    super || self.data.key?(attribute)
  end
end
class Profile < ActiveRecord::Base
  store :data, accessors: [:name], coder: JSON
end