0

I'm a bit stuck with i18n for enum in namespaced model. At the moment I have line in model /app/media/medias.rb like this:

enum territory: { local: 1, global: 2 }

in modal window /views/media/medias/_newmedia.html.erb I have this:

<%= f.select :territory, Media::Medias.territories.keys.collect 
{ |g| [(t'.territories.#{g.downcase}'), g] }, {}, {class:"form-control m-b"} %>

and in /config/locales/models/medias.en.yml I have this:

en:
  media:
    medias:
      territories:
        local: Local_EN
        global: Global_EN

In console I see query is done, no error is thrown, but my view does not appear. When I change to simple Media::Medias.territories.keys I get drop-down in view with key values in my view. How do I fix this, please? Thank you!

So far I've tried to implement code from this answer. In view it gives translation nicely, however on create action I received error as it tried to save not enum key, but localized value.

The solution

Ok, it appears this answer is solution in my case. If anyone needs here is how it should be done with namespaced model on my example:

1) in model /app/media/medias.rb

enum territory: { local: 1, global: 2 }

def self.territory_attributes_for_select
  territories.map do |territory, _|
    [I18n.t("activerecord.attributes.#{model_name.i18n_key}.territories.#{territory}"), territory]
  end
end

2) then in view partial /views/media/medias/_newmedia.html.erb

<%= f.select :territory, options_for_select(Media::Medias.territory_attributes_for_select), 
{}, {class:"form-control m-b"} %>

3) and finaly in /config/locales/en.yml

en:
  activerecord:
    attributes:
      media/medias: #Important! This is how you define namespaced model!
        territories:
          local: "Local EN"
          global: "Global EN"

I can confirm correct locale is shown in view and then values are saved in create action.

Community
  • 1
  • 1
matiss
  • 747
  • 15
  • 36
  • `'.territories.#{g.downcase}'` should use double quotation. – wesley6j Feb 12 '17 at 11:52
  • @wesley6j Ok, I changed and now I can see view where there is enum value with first capital letter in dropdown, e.g., `Local` I still can't get my translation in view. – matiss Feb 12 '17 at 12:04
  • That is I18n problem with partial, check out this: [Trouble on using the i18n gem with partial template files](http://stackoverflow.com/questions/8767706/trouble-on-using-the-i18n-gem-with-partial-template-files) – wesley6j Feb 12 '17 at 12:13
  • @wesley6j Do you think so? I can have static text localized in same partial. Problem I have is with enum particularly. I tried to use one piece of code which I link to in my question, but it does not work when saving form. – matiss Feb 12 '17 at 12:22
  • `f.select :territory, collection: Media::Medias.territories...` – wesley6j Feb 12 '17 at 12:50
  • @wesley6j I added solution which worked for me. – matiss Feb 12 '17 at 16:32

0 Answers0