Skip to content

Instantly share code, notes, and snippets.

@mimosa
Last active August 29, 2015 14:08
Show Gist options
  • Save mimosa/3ed7d3c72c166089f10e to your computer and use it in GitHub Desktop.
Save mimosa/3ed7d3c72c166089f10e to your computer and use it in GitHub Desktop.
元编程,数据库多语言方案

新增方法

class ActiveRecord::Base
  def self.has_translation(*attributes)    
    attributes.each do |attribute|
      define_method "#{attribute}" do
        self.send "#{attribute}_#{I18n.locale.to_s.downcase.sub('-','_')}"
      end
    end
  end
end

Model 中指定字段名

has_translation :name, :title

取数据时根据当前 locale 获取字段内容。

@instance.name # calling @instance.name_en if locale = :en
               #         @instance.name_jp if locale = :jp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment