Search code examples
ruby-on-railsinternationalizationruby-on-rails-3.2ransack

How to get I18n Attributes working with Ransack without the locale file?


I'm using Rails 3.2 with Ransack 0.7 for searching my database and I came across a problem with the displayed names of the attributes for my models. My attribute fields in the view are called in the standard condition field:

<%= f.attribute_fields do |a| %>
  <%= a.attribute_select( {}, { :class =>"formee-small" } ) %>
<% end %>

And in the model my attribute fields are defined by this:

UNRANSACKABLE_ATTRIBUTES = ["id"]

def self.ransackable_attributes auth_object = nil
  (column_names - UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
end

Now let's say I have an attribute called "username", which in my view would be displayed as "Username". Now if I want to translate it I need to put the translation in my standard locale file, which would be en.yml for the english and de.yml for the german version of my website.

Now here's the problem:

This solution works fine as long as I know my models and their attributes. But I have a very complex application, which allows the user to create his own MVC's (Model, View and Controller) and with that his own translations. In every case this works fine, except for the displayed name in a Ransack search form for the user created MVC.

So, possible solutions would be:

1) I find a way to update my locale files every time the user creates a new MVC and every time he changes one of the translations for the attributes.

2) I bypass the locale file and tell Ransack or Rails directly what the correct names for my attributes.

For either way I haven't found any method to do this, so if anyone has a solution I would really appreciate it. Other solutions are welcomed as well.

Thanks in regards!


Solution

  • If anyone wants to know, I changed the translate.rb file from ransack in

    lib/ransack/translate.rb 
    

    and replaced the normal

    t("translation key")
    

    with

    I18n.t("translation key")
    

    and now I can read the attributes from my database, if they have the following key:

    ransack.attributes.NAME_OF_THE_ATTRIBUTE
    

    Maybe not the best way, but it works fine for me!