剥离不相关的部分,我有以下模型:
class Member < ActiveRecord::Base
attr_accessible :custom_fields_attributes
has_many :custom_fields, :as => :custom_fieldable
end
class CustomField < ActiveRecord::Base
attr_accessible :key_id, :value
belongs_to :key
belongs_to :custom_fieldable, :polymorphic => true
end
class Key < ActiveRecord::Base
attr_accessible :key
end
假设我的keys
表中有两个条目:
---------------
id | key
---+-----------
1 | Hair color
2 | Height
如何运行一个查询,让我检索所有“棕色”头发颜色和“5英尺”高度的成员?
我尝试将其作为两个连续的命令:
ms = Member.joins(:custom_fields).where("custom_fields.key_id = 1 AND custom_fields.value = 'Brown'")
ms.joins(:custom_fields).where("custom_fields.key_id = 2 AND custom_fields.value = '5ft'")
但是,这不起作用,因为ActiveRecord运行第二个查询,如下所示:
SELECT `members`.* FROM `members` INNER JOIN `custom_fields` ON
`custom_fields`.`custom_fieldable_id` = `members`.`id` AND
`custom_fields`.`custom_fieldable_type` = 'Member' WHERE
(custom_fields.key_id = 1 AND custom_fields.value = 'Brown') AND
(custom_fields.key_id = 2 AND custom_fields.value = '5ft')
上面的查询返回一个空记录,因为没有自定义字段可以同时同时处理两件事。
我想要做的是让Rails评估第一个结果,然后对其运行第二个查询。我该怎么做?
我使用的版本是Rails 3.2.14。
答案 0 :(得分:1)
如果您想在一个查询中执行此操作,我怀疑您必须为加入custom_fields
表的时间中的一个(或两个)设置别名。
类似的东西:
Member
.joins('custom_fields as custom_fields_1').where("custom_fields_1.key_id = 1 AND custom_fields_1.value = 'Brown'")
.joins('custom_fields as custom_fields_2').where("custom_fields_2.key_id = 2 AND custom_fields_2.value = '5ft'")
或者,分别运行两个查询,然后合并结果。例如
brown_members = Member.joins(:custom_fields).where("custom_fields.key_id = 1 AND custom_fields.value = 'Brown'")
height_members = Member.joins(:custom_fields).where("custom_fields.key_id = 2 AND custom_fields.value = '5ft'")
ms = brown_members.merge(height_members)