Rashed Al-Julaibi
Rashed Al-Julaibi

Reputation: 281

How to order records according to an attribute from associated model - Rails 4

I have a Grade model and a Course model with the following associations:

class Grade < ActiveRecord::Base
    resourcify
    has_many :courses
end


class Course < ActiveRecord::Base
    resourcify
    belongs_to :grade
    has_many :chapters, dependent: :destroy
    has_many :packages, dependent: :destroy
    belongs_to :subject
end

I have a grade_number column in my Grade table, and I would like it so that when I display all courses in course index page, they are ordered by grade_number in descending order. Here is my course#index:

      def index
       @grades = Grade.all
       @subjects = Subject.all
       @courses = Course.includes(:grades).order("grade.grade_number DESC")
      end

Which is giving me the following error:

Association named 'grades' was not found on Course; perhaps you misspelled it?

and index.html.erb :

        <% @courses.each do |course| %>
          <div class="col-md-4">
            <div class="course_info">
              <div class="top_titles">Grade <%= course.grade.grade_number %></div>
              <div class="subject"><%= course.subject.name if course.subject and course.subject.name%></div>  
              <div class="semester"><%= course.semester %> Semester</div>
              <div class="button_wrapper"><%= link_to "View Course", [course.grade, course], :class => "course_button" %></div>
              <% if can? :update, :destroy, @course %>
                <div class="admin-links">
                  <%= link_to 'Edit', edit_grade_course_path(course.grade, course) %> |
                  <%= link_to 'Destroy', [course.grade, course], method: :delete, data: { confirm: 'Are you sure?' } %>
                </div>
              <% end %>
            </div>
          </div>
        <% end %>

Upvotes: 0

Views: 181

Answers (3)

Narasimha Reddy - Geeker
Narasimha Reddy - Geeker

Reputation: 3890

removes s in :grades

@courses = Course.includes(:grade).order("grades.grade_number DESC")

it will work. try like this.

Upvotes: 2

dp7
dp7

Reputation: 6749

Thanks @tadman

includes should take association name and order should take table name i.e

courses = Course.includes(:grade).order("grades.grade_number DESC")

Upvotes: 1

Qaisar Nadeem
Qaisar Nadeem

Reputation: 2424

  def index
       @grades = Grade.all
       @subjects = Subject.all
       @courses = Course.includes(:grade).order("grades.grade_number DESC")
  end

Please note that Association name in Course is grade not grades Course belongs to grade so it is singular.

Upvotes: 3

Related Questions