1

I have the following models in my Rails application:

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

I must query tests belonging to particular ClassProfile. My present helper function is like this:

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

In my erb file, I am looping through the result like this:

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

But the problem here is I am getting all the tests names and not the only ones associated with that particular ClassProfile. How can I correct it so that it functions that way I want it to?

7
  • 1
    'tests belonging to particular ClassProfile' - it sounds like all you need is class_profile.tests. Commented May 30, 2019 at 10:13
  • I want to query it from TestProfile. How can I do that? Commented May 30, 2019 at 10:23
  • I have edited the question now. Commented May 30, 2019 at 10:24
  • I don't understand your data model at all. You have Test associated many to one to ClassProfile? Commented May 30, 2019 at 10:34
  • 1
    You have a typo somewhere - has_many :tests_profiles but class TestProfile. Note difference between test and tests, it should be the same for both cases Commented May 31, 2019 at 6:25

1 Answer 1

1

You can use has_many through here:

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

and use class_profile.tests.each do in the view

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.