0

我希望能够在作为哈希的非数据库模型上具有虚拟属性。我只是不知道从这个哈希中添加和删除项目的语法是什么:

如果我定义:

attr_accessor :foo, :bar

然后在模型中的一个方法中,我可以使用:

self.foo = "x"

但我不能说:

self.bar["item"] = "value"
4

4 回答 4

2

尝试

self.bar = Hash.new
self.bar["item"] = "value"
于 2012-09-27T20:03:43.037 回答
1
class YourModel
  def bar
    @bar ||= Hash.new
  end

  def foo
    bar["item"] = "value"
  end
end

但经典的方法是:

class YourModel
  def initialize
    @bar = Hash.new
  end

  def foo
    @bar["item"] = "value"
  end
end
于 2012-09-27T20:28:33.403 回答
0

只需使用OpenStructHash with Indifferent AccessActive Model

于 2012-09-27T19:56:58.503 回答
0

当你打电话时:

attr_accessor :foo, :bar

在你的课堂上,Ruby 在幕后做了如下的事情:

def foo
  return @foo
end
def foo=(val)
  @foo = val
end

def bar
  return @bar
end
def bar=(val)
  @bar = val
end

#foo 和 #bar 方法只是返回实例变量,而 #foo= 和 #bar= 只是设置它们。因此,如果您希望其中一个包含哈希,则必须在某处分配此哈希。

我最喜欢的解决方案如下:

class YourModel

  # generate the default accessor methods
  attr_accessor :foo, :bar

  # overwrite #bar so that it always returns a hash
  def bar
    @bar ||= {}
  end

end
于 2012-09-28T08:39:47.980 回答