Skip to content
Seb Bacon edited this page Jan 14, 2011 · 24 revisions

Overriding model field setters

We use the Globalize plugin to localize model fields. Where column "foo" has been marked in the model as :translates, globalize overrides foo.baz = 12 to actually set the value in column baz of table foo_translations.

A side effect of the way it does this is that if you wish to override a specific attribute setter, you will need to explicitly call the Globalize machinery; something like:

    def name=(name)
        globalize.write(self.class.locale || I18n.locale, "name", name)
        self["name"] = short_name
        # your other stuff here
    end

Searching

The find_first_by_<attr> and find_all_by_<attr> magic methods should work. If you want to do a more programmatic search, you will need to join on the translation table. For example:

          query = "#{translated_attr_name(someattr) = ? AND #{translated_attr_name('locale')} IN (?)"
          locales = Globalize.fallbacks(locale || I18n.locale).map(&:to_s)
          find(
            :first,
            :joins => :translations,
            :conditions => [query, value, locales],
            :readonly => false
          )
Clone this wiki locally