Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails I18n with serialized attributes using fields_for

Consider this setup:

#app/models/user.rb
class User > ActiveRecord::Base
  attr_accessible :login, :options
  serialize :options, OpenStruct
end

#app/views/users/_form.html.erb
form_for @user do |f|
  f.label :login
  f.fields_for :options, @user.options do |options|
    options.label :emailme
  end
end 

#config/locals/en.yml
  en:
    activerecord:
      attributes:
        user: 
          login: "User Name"
          options: 
            emailme: "Email Preference"

The problem I'm trying to solve is being able to localize the label tag for an attribute(:emailme) of the serialized attribute "options".

I've dug deep into the rails source and figured out that the problem is because when I call options.label its expects there to be an object, but there is no object because the object name that is passed down is "user[options"] and that is not a valid instance variable name.

See line 1124 of form_helper.rb on rails github where it retrieves the object. There is a comment that even mentions to fallback to nil when object_name is item[subobject].

And so, when it goes to create the actual label Line 1110 form_helper.rb it defaults to method_name.humanize

Is there any decent way to accomplish localization with serialized attributes?

like image 627
Peter P. Avatar asked Oct 06 '22 22:10

Peter P.


1 Answers

Alternatively, I discovered I could use i18n helpers like so(and not have to change anything in the form):

 en:
   helpers:
   label:
    "user[options]":
       emailme: "Email Preference"

Although this still doesn't cover validation messages...

like image 98
Peter P. Avatar answered Oct 10 '22 02:10

Peter P.