我正在使用Ruby on Rails 3.0.7,我想知道如何初始化\ build“自定义”数据结构响应where
方法,就像它工作一样,例如,对于常见的RoR AssociationCollection对象
例如:
# The following code should work after build the 'test_data' as well...
# but how to build that?
test_data.where(:test_attribute => 'test_value')
答案 0 :(得分:1)
我对你所追求的内容并不完全清楚,但你可以创建一个包装器(例如)使用where
进行搜索的哈希数组。
class Search
def initialize(data)
@data = data
end
def where(filters={})
@data.select do |item|
filters.all?{|key, value| item[key] == value }
end
end
end
data = [
{ :name => 'Sam', :age => 27, :gender => 'M' },
{ :name => 'Sue', :age => 27, :gender => 'F' },
{ :name => 'Bob', :age => 32, :gender => 'M' }
]
search = Search.new(data)
search.where(:age => 27) # returns array containing Sam and Sue hashes
search.where(:gender => 'M') # returns array containing Sam and Bob hashes
search.where(:age => 27, :gender => 'M') # returns array containing just Sam