How to override the where method of ActiveRecord properly?

Multi tool use


How to override the where method of ActiveRecord properly?
I already successfully overrode the where
method. The behavior I want to achieve is, if a my hstore
is accessed, it rewrites the where
query in such a way, that the hstore
items are treated as separate columns. Here is my where
method:
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
For that I wrote this minitest
, which works great!
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
Now I wrote another test for the find_by()
methods:
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
Unfortunately this doesn't work. As 'we' already found out there are two different implementation of find_by()
in ActiveRecord. Find_by()
calls the implementation in the core, which creates a ActiveRecord::StatementCache::Substitute
and hands this over to my where
method. I don't know how to deal with this? How can I modify the statement?
find_by()
Find_by()
ActiveRecord::StatementCache::Substitute
where
By the way, this helps me to realize awesome_hstore_translate.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.