Rails-запрос из трех моделей с использованием соединений - PullRequest
1 голос
/ 30 мая 2019

В моем приложении Rails есть следующие модели:

class Test
    has_many :tests_profiles
    has_many :class_profiles

class TestsProfile
    belongs_to :class_profile
    belongs_to :test

class ClassProfile
    has_many :tests_profiles

Я должен запросить tests, принадлежащий конкретному ClassProfile. Моя нынешняя вспомогательная функция выглядит так:

def get_tests(class_profile)
        return Test.joins(:tests_profiles).where(tests_profiles: {class_profile_id: class_profile.id})

В моем erb файле я перебираю результат примерно так:

<% tests = get_tests(class_profile) %>
    <% tests.each do |test| %>
        <th><%= test.name %></th>
    <% end %>

Но проблема здесь в том, что я получаю имена всех тестов, а не только те, которые связаны с этим конкретным ClassProfile. Как я могу исправить это так, чтобы он функционировал так, как я хочу?

1 Ответ

1 голос
/ 31 мая 2019

Вы можете использовать has_many through здесь:

class Test
    has_many :tests_profiles
    has_many :class_profiles, through: :tests_profiles

class TestsProfile
    belongs_to :class_profile
    belongs_to :test

class ClassProfile
    has_many :tests_profiles
    has_many :tests, through: :tests_profiles

и используйте class_profile.tests.each do в представлении

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...