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

Ruby on rails 按值查找列

Ruby on rails 按值查找列,ruby-on-rails,rails-activerecord,Ruby On Rails,Rails Activerecord,我如何执行查询以将孩子拥有的玩具返回为true? 我不想在查询中使用列名,这样我就可以将玩具添加到列表中,并且可以在不指定每个列名的情况下找到任何标记为true的列名。您可以用一个示例来解释这一点吗?我不想在查询中使用列名,这样我就可以将玩具添加到列表中,并且可以在不指定的情况下找到任何标记为true的列名我认为这种数据模型没有多大意义。每当你想到一种新型玩具,就必须在表中添加一列,这不是很好。只使用字符串列玩具类型有什么问题? class Child has_many :toys end

我如何执行查询以将孩子拥有的玩具返回为true?
我不想在查询中使用列名,这样我就可以将玩具添加到列表中,并且可以在不指定每个列名的情况下找到任何标记为true的列名。

您可以用一个示例来解释这一点吗?我不想在查询中使用列名,这样我就可以将玩具添加到列表中,并且可以在不指定的情况下找到任何标记为true的列名我认为这种数据模型没有多大意义。每当你想到一种新型玩具,就必须在表中添加一列,这不是很好。只使用字符串列玩具类型有什么问题?
class Child
  has_many :toys
end


class Toys
  belongs_to :child
end

class CreateToys < ActiveRecord::Migration[5.1]
def change
  create_table :toys do |t|
  t.integer :child_id
  t.boolean :marbles, default: false
  t.boolean :blocks,  default: false
  t.boolean :jacks,   default: false
  t.boolean :dolls,   default: false
  t.timestamps
  end
 end
end

child = Child.first
child.toys.create(marbles=true, blocks=true, jacks=false, dolls=false)
toy_attributes = Toy.new.attributes.keys.select do |key| 
  key != 'created_at' && key != 'updated_at' 
end
params = toy_attributes.reduce({}) do |params, attr| 
  params[attr] = true; params 
end
toys = params.flat_map do |attribute, value| 
  child.toys.where({attribute => value})
end