我有Grade
模型和Course
模型,其中包含以下关联:
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
我的成绩表中有一个grade_number列,我希望这样当我在课程索引页面中显示所有课程时,它们按照grade_number的降序排序。这是我的课程#index:
def index
@grades = Grade.all
@subjects = Subject.all
@courses = Course.includes(:grades).order("grade.grade_number DESC")
end
这给了我以下错误:
协会命名&#39;成绩&#39;在课程中找不到;也许你 拼错了吗?
和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 %>
答案 0 :(得分:3)
def index
@grades = Grade.all
@subjects = Subject.all
@courses = Course.includes(:grade).order("grades.grade_number DESC")
end
请注意Course
中的关联名称为grade
而非grades
课程属于年级,所以它是单数。
答案 1 :(得分:2)
删除s
:grades
@courses = Course.includes(:grade).order("grades.grade_number DESC")
它会起作用。试试这样。
答案 2 :(得分:1)
谢谢@tadman
includes
应该使用关联名称,order
应该采用表名,即
courses = Course.includes(:grade).order("grades.grade_number DESC")