ruby-on-railsmobility

How do I handle a like query using Mobility in Rails?


The title says it all. The goal is to handle a simple search.

Trying to do this in my controller, which worked with Globalize:

query = "%#{query}%"
docs = Doc.i18n.where(category_id: category_ids)
docs = docs.where("title like ?", query)

Based on this model:

class Doc < ApplicationRecord
  extend Mobility
  translates :title, type: :string
end

The following error is the result:

Mysql2::Error: Unknown column 'title' in 'where clause'

I've tried the following, which doesn't throw an error, but doesn't work either (it returns all Doc records):

docs = docs.where("title like #{query}", locale: :en)

And I've tried this, but it doesn't actually seem to query anything (it returns all Doc records):

docs.i18n do
  title.matches(query)
end

I can't find any documentation on how to handle querying with the like operator using Mobility. Any ideas?


Solution

  • The following error is the result:
    

    If that worked in Globalize, it's only because the translations table has a column named title. Strings are not parsed by Mobility (or Globalize) so never expect that hand-crafted SQL will work with translated attributes.

    Doc.i18n { title.matches(query) }
    

    should work (it's in the Mobility readme). If not you've got something else going on in your model.