首页 > 解决方案 > 使用连接从三个模型进行 Rails 查询

问题描述

我的 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. 我怎样才能纠正它,使它按我想要的方式运行?

标签: ruby-on-rails

解决方案


你可以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在视图中使用


推荐阅读