I’m building an app that needs i18n support across the entire database
(i.e. localized attributes). In order to do this I’ve created a
special HABTM join table that can be associated with any other
table:
create table language_strings (
for_table varchar(255) not null,
foreign_id int not null,
language_id varchar(5) not null,
attr_name varchar(255) not null,
value text not null,
primary key (for_table, foreign_id, language_id)
);
Notice the for_table and foreign_id columns. These two are used to
identify the table and row to which each record belongs.
To make this work I then add something like this to each models that
needs it:
class Property < ActiveRecord::Base
has_and_belongs_to_many :names,
:class_name => ‘Language’,
:join_table => ‘language_strings’,
:foreign_key => ‘foreign_id’,
:finder_sql =>
"SELECT language_id AS id, value " +
"FROM language_strings " +
"WHERE for_table = ‘properties’ AND " +
'foreign_id = #{id} AND ’ +
“attr_name = ‘name’”
end
( With pretty highlighting: http://rafb.net/paste/results/n5aV2A60.html
)
Ok, now the problem. The above code does work, however, after fetching
the first Property all succesive ones issue the exact same query
(the one from finder_sql), meaning it doesn’t change the id (in
'foreign_id = #{id} AND ') and keeps bringing the same values.
A script/console example:
p1 = Property.find 1
p1.names
=> [#<Language:0xa742c4f4 @attributes={“id”=>“en”, “value”=>“Color”}>]
p2 = Property.find 2
p2.names
=> [#<Language:0xa742828c @attributes={“id”=>“en”, “value”=>“Color”}>]
In the last line “value” should be “Size”, not “Color”.
Checking the logs I noticed it keeps using id = 1 ever after the first
query.
I really need this to work, but have run out of ideas. Any gurus out
there willing to help? Could this be a bug in Rails or some cache
feature I’m missing?
Thanks in advance,
Pedro F.