Rails store categories in different languages - ruby-on-rails

I'm building a multilang application that has two essential models Category and Product, where a Category has many Products..
So I want the ability to display the same categories with more than a language, for example, consider a category called Cars, it should be presented as Vehicules for a user using the french version of the application.
How could I do that? Should I store them in different models? or should I add a lang column in the Category model ?
What I thought of doing is adding a lang column in the Category model and add a default_scope call to scope it to search for only the desired language, I have two questions though:
How can I get the used language from inside a model, an I18n call ? Which method should I call on it ?
A problem arises from using this technique, a product which references a category in french wouldn't show up in a search under the category in english, how can I resolve this issue ?
Thank you

The key question you have to ask yourself is whether it's important that the Cars category should be the same object (implying the same object and the same URL) as the Vehicules category or not.
If they should be the same category, then the only question is how you translate the name into different languages. If you have a relatively small number of languages to support, you could simply store them all on the model using different columns (name_en, name_fr, etc).
Or you could store the translated names separately, such as using the I18n modules.
Alternatively, if Cars and Vehicules are separate categories, then you could follow your suggestion of adding a lang attribute to the model.

Frankie Roberto gave you a good answer. I will just add some additional info.
First the easy part: getting current locale in a model.
If you set the language in a controller as I18n.locale = something, then you may read it in a model the same way. The I18n is a global constant, after all.
Now about searching:
I generally prefer the designs where you have one category, but the name of the category is translated to many languages. The design where one car belongs to category "Cars" and another one belongs to "Vehicules" is flawed IMHO. In the later case there is no sense of making it a single site - you could create a one-language application, and install it in multiple instances, where every one is translated to a single language.
If you have a short, static list of supported languages, you may add a column for every language: name_en, name_fr, name_pl.
If your list of languages will be large or unknown at the moment of designing your application, it would be easier to store the "name" (given as an example) as a serialized hash. So, you could get the intended translation as name["fr"], name["de"] and so on.
I have already learned (the hard way :-) ) that users usually are too lazy to provide all the translations (or they just do not know all the languages), so you should be prepared that some of your models will not have the data in a language you are trying to display or search.
For every 'translated' attribute you may want to prepare a method which will supply you with the most appropriate translation in case the required one is missing.
This method may work in a way similar to:
def translated_name
([I18n.locale] + other_languages).each do |l|
return name[l] unless name[l].blank?
end
return "" # or some default value - possibly from I18n.t("some.static.default")
end
Of course, you do not need to use I18n.locale, and you should define other_languages in a way which would (ideally) match user language preferences, possibly by analyzing the "Accept-Language" header.
I sometimes use the method name name_for(lang) or name_in(lang), if I have to support more languages for data than for interface (which I shall translate and put in I18n config files).
Ah, yes - searching. :)
If you have defined the "names" as separate attributes, you may just search the appropriate column.
If you have the "names" as a single, serialized hash, you may search the column as a simple text (however I am not sure whether YAML will not mangle the non-ASCII characters) or create another column with searchable data, and then (at the model-level, not at the SQL level) partition the models into groups: "The search string has been found in your language", "The search string has been found in some other language". I believe the user of multi-lang service will be happy with search results presented in this way.

i'm using this gem to solve this kind of problem: https://github.com/jo/puret

Related

Best practices regarding per-user settings and predefining options

I want to save settings for my users and some of them would be one out of a predefined list! Using https://github.com/ledermann/rails-settings ATM.
The setting for f.e. weight_unit would be out of [:kg, :lb].
I don't really want to hardcode that stuff into controller or view code.
It's kind of a common functionality, so I was wondering: Did anyone come up with some way of abstracting that business into class constants or the database in a DRY fashion?
Usually, when I have to store some not important information which I don't care to query individually, I store them on a serialized column.
In your case you could create a new column in your users table (for example call it "settings").
After that you add to user model
serialize :settings, Hash
from this moment you can put whatever you like into settings, for example
user.settings = {:weight_unit => :kg, :other_setting1 => 'foo', :other_setting2 => 'bar'}
and saving with user.save you will get, in settings column, the serialized data.
Rails does also de-serialize it so after fetching a user's record, calling user.settings, you will get all saved settings for the user.
To get more information on serialize() refer to docs: http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html#method-i-serialize
UPDATE1
To ensure that settings are in the predefined list you can use validations on your user model.
UPDATE2
Usually, if there are some pre-defined values it's a good habit to store them in a constant inside the related model, in this way you have access to them from model (inside and outside). Acceptable values does not change by instance so it makes sense to share them between all. An example which is more valuable than any word. Defining in your User model:
ALLOWED_SETTINGS = {:weight_unit => [:kg, :lb],
:eyes_color => [:green, :blue, :brows, :black],
:hair_length => [:short, :long]}
you can use it BOTH
outside the model itself, doing
User::ALLOWED_SETTINGS
inside your model (in validations, instance methods or wherever you want) using:
ALLOWED_SETTINGS
Based on your question, it sounds like these are more configuration options that a particular user will choose from that may be quite static, rather than dynamic in nature in that the options can change over time. For example, I doubt you'll be adding various other weight_units other than :kg and :lb, but it's possible I'm misreading your question.
If I am reading this correctly, I would recommend (and have used) a yml file in the config/ directory for values such as this. The yml file is accessible app wide and all your "settings" could live in one file. These could then be loaded into your models as constants, and serialized as #SDp suggests. However, I tend to err on the side of caution, especially when thinking that perhaps these "common values" may want to be queried some day, so I would prefer to have each of these as a column on a table rather than a single serialized value. The overhead isn't that much more, and you would gain a lot of additional built-in benefits from Rails having them be individual columns.
That said, I have personally used hstore with Postgres with great success, doing just what you are describing. However, the reason I chose to use an hstore over individual columns was because I was storing multiple different demographics, in which all of the demographics could change over time (e.g. some keys could be added, and more importantly, some keys could be removed.) It sounds like in your case it's highly unlikely you'll be removing keys as these are basic traits, but again, I could be wrong.
TL;DR - I feel that unless you have a compelling reason (such as regularly adding and/or removing keys/settings), these should be individual columns on a database table. If you strongly feel these should be stored in the database serialized, and you're using Postgres, check out hstore.
If you are using PostgreSQL, I think you can watch to HStore with Rails 4 + this gem https://github.com/devmynd/hstore_accessor

Which approach should I use to store translation of products in database?

I'm creating an application where products will be created by my customer (something like an e-commerce website), so I obviously require translated descriptions stored in database, I can't force my customer to learn git/yml.
I have two ideas on how to correctly localize descriptions (and eventually product name) and store them in database, but if there is a well-known approach that I should use, I would be really happy to know it.
The first idea seems the most logical for me, but I would like to make it "transparent" to me, I don't want to write joins everywhere, so some suggestion on how to achieve this, if it's the correct one, would be appreciated.
Idea 1:
Create a database table products (with name and description field set maybe to the default locale language), then a products_translations table which contains a table structured in this way:
products_translations
- id
- locale
- product_id
- name
- description
As an example: product_translation: { id: 1, locale: 'en', product_id: 3, name: 'toy', description: 'play' }
But I want to access to translations without the requirement to write a lot of IFs everywhere. So if I write product.name it should return en or it based on current locale.
Bonus: Are there any gems that can help me to achieve this?
Idea 2: The other idea is to have a table with name_locale1, name_it and so on, but I don't like this approach because will pollute my model objects with fields and I will have a giant table.
However, in this way I can avoid join on every query for that object.
If there is a greater approach which I don't know about (a database pattern or similar), it's ok that too, I'm not forced to strict to only these two ideas, however I have to choose between the two and I really don't know which could be better.
Important: I would like to keep translations stored in yml files, except for dynamic contents, which obviously require translations in database.
I agree with PinnyM that the first approach is the better of the two, but rather than implement your own schema, I would highly recommend you implement Globalize3 where most of the structural decisions have been taken for you (and by Mr Fuchs himself, no less). Also, with the rails helpers, you just call something like product.name on a model instance and the gem will figure out how to display it in the correct locale, awesome!
The first approach is the recommended one. As you surmised, the second approach is not as clean and requires more work on the coding end with no real gain since you still have to join on this monster table. To the contrary, the first method requires at most one join, while the second approach requires a join on each attribute you may want to add localization support.
You can simply append a scope on all your product calls such as:
scope :for_locale, lambda{|locale| joins(:product_translations).
where(product_translations: {locale: locale || 'en'}) }
and pass in the session locale (or wherever you are storing it).

Rails 2.2 translation plugin/gem

I'm looking for a localisation system to use in a rails 2.2.2 app that i manage. I think i've seen one before that does exactly what i want but i can't manage to find it with google.
The system i have in mind works as follows: any ActiveRecord model (or perhaps a list of specified models, listed in a config file for example) can have a translation record associated with it, which specifies a locale and the new values for one or more of the fields in that record, for the listed locale. Please note this is a seperate sort of problem to that solved by i18n: it's a way of setting locale-specific data, rather than locale-specific names of fields or similar "system-level" strings.
For example, let's say my site provides music lessons. In the UK (the default locale), musical notes which last one "beat" are called "crotchets"* while in the US they're called "quarter notes". So, i might have a lesson that has this data:
#a Lesson object, with an entry in the "lessons" table in the db
id: 1234
name: "My Lesson"
description: "In this lesson you'll learn about crotchets."
and I want this translation record associated with it:
id: 1
translatable_type: "Lesson"
translatable_id: 1234
locale: "US"
data: {:description => "In this lesson you'll learn about quarter notes"}
Now, when i view the lesson, the system checks the current locale, and sees if there's any current-locale-specific data for this lesson, sees that there is (the description) and displays that instead of the standard description.
Has anyone seen a system like this?
thanks, max
PS - in this example i've done a simple string substitution of "crotchets" to "quarter notes", which might tempt the reader to think i just need some kind of simple string substitution translation. But that's not the case - some of the US-specific names/descriptions will be quite different to their uk counterparts and so require a completely customisable us-facing name, description, etc.
*this might not be exactly musically true in all cases but that's outside the scope of this question :)
I think that Globalize2 may be what you are after for locale-specific data solutions (I've had success using Globalize3 for my Rails 3.2 apps). If not, then hopefully the alternative solutions section on Globalize2's Github repo README file will provide something else that will work for you with Rails 2.2. Good luck!

Implement dynamic data model with MongoDB in Rails

I'm creating an application consisting of a bunch of entries. These entries are going to have a bunch of fields (e.g. category, name, description etc.) and be of a certain type (category). So the user would first create a category with a title and description and then define what other fields an entry in that category can and should have.
Example:
Create category, title => 'Books', description => 'A description'. Defining extra fields, author (required), image (not required).
Create entry, when choosing category => 'Books' the form is regenerated and the fields for author and image are shown with validation defined in the category.
I hope somebody understands..
I was talking to a friend about this who recommended going for MongoDB in order to implement this, now I have an app installed with Mongoid and everything works just fine.
The question is, how would I implement this in the best way, making it as flexible as possible?
it's hard to answer to your because it is quite vague… here is what I can say about MongoDB:
MongoDB is already as flexible as possible (that is even its problem actually).
The problem is more likely to sometime restricts its flexibility i.e. check access rights, check that your jSON you are storing is in the right scheme and so on.
If your db is not too huge and you do not want to bother with many collections, you can store all your Books items (documents) (or even a document containing lists) into the same collection.

Rails: translations for table's column

In rails application I have two models: Food and Drink.
Both food and drink have a name, which has to be stored in two languages.
How do I better realize translations for theese tables?
First solution I realized was to replace name column with name_en and name_ru.
Another solution is to encode with YAML hash like { :en => 'eng', :ru => 'rus' } and store yaml as a name.
What would you recommend, assuming content is not static?
Maybe there's good article?
The first option (name_en, name_ru) is the easiest to implement.
You could include a name method that returns the right value depending on the selected locale. You could even create a module, if you are going to use this on lots of models/fields:
class Food < ActiveRecord::Base
...
def name
self.send("name_#{I18n.locale}")
end
end
If in the future you must include an additional language, you will have to add a migration, of course. But that shoudn't be too troublesome.
The second one (encoding using YAML) seems a bit more cumbersome - you will not have to make an additional migration with it, but you loose other functionality. For example, search is made much more difficult - you can't use SQL any more for looking through descriptions, as they are coded on YAML instead of being plain text.
So I recommend having two fields.

Resources