如何正确覆盖ActiveRecord的where方法?

时间:2016-07-22 17:10:58

标签: ruby-on-rails ruby activerecord

我已成功覆盖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

0 个答案:

没有答案