create table foo (id, name)
create table foo_config (id, foo_id, key, value)
insert into foo (1, 'name1')
insert into foo (2, 'name2')
insert into foo (3, 'name3')
insert into foo_config (1, 1, 'key1', 'val1')
insert into foo_config (2, 1, 'key2', 'val2')
insert into foo_config (3, 1, 'key3', 'val3')
insert into foo_config (4, 2, 'key1', 'val1')
insert into foo_config (5, 3, 'key2', 'val2')
如何查询key1 = 'val1'
的所有foo,在我们的例子中为foo:1
和foo:2将在这里列出。我应该如何建模/查询,
感谢任何指针。
答案 0 :(得分:0)
首先,您必须构建模型,并设置关联:
class Foo < ActiveRecord::Base
has_many :foo_configs, :dependent => :destroy
end
class FooConfig < ActiveRecord::Base
belongs_to :foo
end
以下是设置查询的方法:
Foo.where(:foo_configs => {:key => 'key1', :value => 'value1'}).includes(:foo_configs)