Rails多模型关联查询异常:无法获取指定ClassProfile关联的Test
First, let's address the root of the issue: your model associations aren't properly defining the many-to-many relationship between Test and ClassProfile via the TestsProfile join model. This is likely causing unexpected behavior in your query.
Step 1: Correct Model Associations
Update your models to use the through keyword to explicitly define the indirect association:
# app/models/test.rb class Test < ApplicationRecord has_many :tests_profiles has_many :class_profiles, through: :tests_profiles # Add this line end # app/models/class_profile.rb class ClassProfile < ApplicationRecord has_many :tests_profiles has_many :tests, through: :tests_profiles # Add this line end
With these changes, Rails will automatically handle the join logic for you, making it trivial to access associated tests.
Step 2: Simplify Your View Code
You can now ditch the helper function entirely and directly access the tests from the class_profile instance in your ERB template:
<% class_profile.tests.each do |test| %> <th><%= test.name %></th> <% end %>
If You Need to Keep the Helper Function
If you prefer to retain the helper for some reason, fix the query to ensure it correctly filters tests and adds distinct to avoid duplicate entries (in case multiple join records link the same test to the class profile):
def get_tests(class_profile) Test.joins(:tests_profiles) .where(tests_profiles: { class_profile_id: class_profile.id }) .distinct # Prevents duplicate test objects from multiple join entries end
Why Your Original Query Failed
A few possible reasons your original code returned all tests:
- Missing
throughAssociation: Without specifyingthrough, Rails was confused about howTestandClassProfilerelate, leading to incorrect query construction. - Unintended Scope: If you have a default scope on the
Testmodel, it might have overridden your where clause (check fordefault_scopein yourTestclass). - Typos: Double-check that your
tests_profilestable has aclass_profile_idcolumn (it should, sinceTestsProfilebelongs_to :class_profile).
内容的提问来源于stack exchange,提问作者Lax_Sam

