Davide Targa website

Programming, web development and open source

I18n for Non ActiveRecord (Tableless) Models

Let’s suppose to have a message model with the following attributes: name, email, content. This model is used to implement a contact form. Obviously this model doesn’t require a table, so you need to use a tableless model.

If you have ever used a tableless model in Rails 3, you should have written something like this in your message model:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Message

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :content

  validates :name, :presence => true
  validates :email, :presence => true, :format => {:with => /^([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i}
  validates :content, :presence => true

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

end

To add internationalization to this type of model you can’t use the normal ActiveRecord way, because this isn’t an ActiveRecord model. The solution to add i18n to tableless models is to add a file called like your locale inside config/locales/models (let’s suppose it), so it.yml. The structure of the yml file to translate the previous message model is the following:

1
2
3
4
5
6
7
it:
  activemodel:
    message: "Messaggio"
  attributes:
    name: "Nome"
    email: "Email"
    content: "Testo"

Hope this helps! :–)

Comments