Yshmarov
Yshmarov

Reputation: 3729

Rails filter dependent data through controller

Problem: I want to show only upcoming attendances (not past ones) in student/show.

I have

-scaffold lesson name starts_at:datetime ends_at:datetime,

-scaffold attendance student:references lesson:references,

-scaffold student name.

student has_many :attendances, lesson has many :attendances, student has_many :lessons, through: :attendances

I tried

students_controller.rb:

@future_attendances = @student.attendances.where('lesson.starts_at > ?', Time.now)

student/show.html.haml:

      %table
        %thead
          %tr
            %th Title
            %th Starts at
        %tbody
          - @future_attendances.each do |attendance|
            %tr
              %td= attendance.lesson.name
              %td= attendance.lesson.starts_at

But it does not work. Any ideas?

Upvotes: 0

Views: 29

Answers (1)

GoGoCarl
GoGoCarl

Reputation: 2519

Shot in the dark, can you not just do:

@future_lessons = @student.lessons.where('starts_at > ?', Time.now)

Then:

%tbody
  - @future_lessons.each do |lesson|
    %tr
      %td= lesson.name
      %td= lesson.starts_at

Your current code doesn't work because you are looking for a column in the lesson table. You would need to use the joins method to add the lesson table to the query to make that work. But, again, I think the line above is what you really want.

Upvotes: 1

Related Questions