我已成功覆盖where
方法。我想要实现的行为是,如果访问了我的hstore
,它会以这样的方式重写where
查询,hstore
项被视为单独的列。这是我的where
方法:
def where(opts = :chain, *rest)
if opts == :chain
WhereChain.new(spawn)
elsif opts.blank?
return self
elsif opts.is_a?(Hash)
translated_attributes(opts).each do |attribute|
return spawn.where!("'#{opts[attribute]}' = any(avals(#{attribute}))", rest)
end
else
super(opts, rest)
end
end
为此,我写了这个minitest
,效果很好!
def test_where_query_with_translated_value
PageWithFallbacks.create!(:title_raw => {'en' => 'English title', 'de' => 'Deutscher Titel'})
exp = PageWithFallbacks.create!(:title_raw => {'en' => 'Another English title', 'de' => 'Noch ein Deutscher Titel'})
res = PageWithFallbacks.where(title: 'Another English title').first
assert_equal(exp.id, res.id)
end
现在我为find_by()
方法编写了另一个测试:
def test_find_by_query_with_translated_value
PageWithFallbacks.create!(:title_raw => {'en' => 'English title', 'de' => 'Deutscher Titel'})
exp = PageWithFallbacks.create!(:title_raw => {'en' => 'Another English title', 'de' => 'Noch ein Deutscher Titel'})
res = PageWithFallbacks.find_by(title: 'Another English title')
assert_equal(exp.id, res.id)
end
不幸的是,这不起作用。 As 'we' already found out there are two different implementation of find_by()
in ActiveRecord. Find_by()
调用核心中的实现,创建ActiveRecord::StatementCache::Substitute
并将其移交给我的where
方法。我不知道如何处理这件事?我该如何修改声明?
顺便说一句,这有助于我实现awesome_hstore_translate。