V
V
vadimstroganov2016-08-04 13:54:12
Ruby on Rails
vadimstroganov, 2016-08-04 13:54:12

Globalize gem + SQL, how to get field value without calling gem methods?

I use the Globalize gem for multilingualism.
There are many heavy queries that end up being written in pure SQL.
Model:

class Page < ActiveRecord::Base
  translates :h1, :title, :content
end

There are two tables:
1) pages - everything is stored here except translations
2) page_translations - page translations are stored here (h1, title, content)
If I do this:
page = Page.first # запрос на получение страницы
page.title # тут произойдет еще один запрос в таблицу page_translates для получения переводов для текущей локали

then there will be two queries, everything is logical, because we did not receive an additional title, h1 or content
But if I want to write, for example, such SQL:
SELECT * FROM pages p JOIN page_translations pt ON pt.page_id = p.id LIMIT 1

In this case, all the data is pulled up, and the main info about the page and its translations, but if we now do this:
sql_page.title
Then there is still a request to the page_translations table to receive the translation (despite the fact that we have already received the necessary fields)
I would not want to refuse from the gem, but I would like to understand how you can simply read the received attribute without triggering the events that the gem does.
I tried this:
sql_page.read_attribute(:title)
It doesn't work, it still makes a request

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Dyachuk, 2016-08-09
@Renius

page.with_translations(I18n.locale)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question