V
V
vadimstroganov2016-06-17 19:41:59
Ruby on Rails
vadimstroganov, 2016-06-17 19:41:59

Has_many like belongs_to?

Hello!
The question is. There is a pages table and page_translations

class Page < ActiveRecord::Base
  has_many :page_translations
end

class PageTranslation < ActiveRecord::Base
  belongs_to :page
end

There are several translations of one page
page_id | locale | title | content
in the table. Is it possible to somehow join pages for the current locale?
That is, now I do this:
@page = Page.joins(:page_translations).first
@page.title # так не могу вытащить title, который берется из таблицы page_translations, тк он вытащил не одну запись, как я понимаю

How to make such a join so that I have access to the title and content?
In SQL I did this:
SELECT *
      FROM pages p
      JOIN page_translations pt
        ON pt.page_id = p.id
      WHERE p.parent_id = ?
        AND p.is_published = ?
        AND pt.locale = ?
      ORDER BY p.lft DESC

But I would like to understand how to do this through ORM

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vadimstroganov, 2016-06-20
@vadimstroganov

Did it like this:

has_one  :page_translation, -> (object){ where("locale = ?", I18n.locale) }

P
Pavel Grudinkin, 2016-06-18
@Hunt666

I don’t really understand why there are joins here, the id of the desired page is already known, isn’t it?

@page = PageTranslation.where(page_id: 123, locale: "en")
@page.title

then it turns out something like:
first in this case will select one page with all its translations
where in this form is not needed, because joins(:page_translations) will already make a request with page_translations.page_id = page.id
@page.page_translations.first, instead of first, any condition can be, as if we were making a request to the database

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question