Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.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 初始化\生成一个";海关;响应“where”方法的数据结构_Ruby On Rails_Ruby_Ruby On Rails 3_Collections_Where - Fatal编程技术网

Ruby on rails 初始化\生成一个";海关;响应“where”方法的数据结构

Ruby on rails 初始化\生成一个";海关;响应“where”方法的数据结构,ruby-on-rails,ruby,ruby-on-rails-3,collections,where,Ruby On Rails,Ruby,Ruby On Rails 3,Collections,Where,我正在使用Ruby on Rails 3.0.7,我想知道如何初始化\构建“自定义”数据结构,以响应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_valu

我正在使用Ruby on Rails 3.0.7,我想知道如何初始化\构建“自定义”数据结构,以响应
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')

我不完全清楚您想要的是什么,但是您可以在(例如)使用
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

你是在问变量名吗?我想你希望在单元测试中有这样的行为?如果是这样,考虑简单地模仿你的模型和它的方法。否则我不知道:)@jaydel-不,“test”只是一个名字。