我有两个模型,Subject
和Course
。一个Course
belongs_to aSubject
和一个Subject
has_many Courses
。创建新课程时,我使用 collection_select 来获取数据库中的所有主题,以便选择课程所属的主题。这工作正常,但是我在从课程 index.html 页面中显示获取 subject.name 时遇到问题,而我只能让其 id 出现。我试过做 <%= course.subject.name %> 这给了我一个错误:nil:NilClass 的未定义方法“名称”。我应该怎么做才能在课程视图页面中显示 subject.name?
这是我的代码:
课程形式:
<div class="field">
<%= f.label "Subject" %>
<%= collection_select :course, :subject_id, Subject.all, :id, :name %>
</div>
索引.html:
<div class="courses">
<div class="semesters">
<h3>Courses</h3>
<% @grade.courses.each do |course| %>
<div class="course_group">
<div class="course_list">
<h3><%= course.subject.name %></h3>
<p><%= course.title %></p>
<%= link_to "View Course", [@grade, course], :class => "button button_orange" %>
<div class="course_links">
<% if can? :update, @course %>
<%= link_to 'Edit', edit_grade_course_path(@grade, course) %> |
<% end %>
<% if can? :destroy, @course %>
<%= link_to 'Destroy', [@grade, course], method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
</div>
</div>
</div>
<% end %>
</div>
<div class="create_course">
<% if can? :create, @course %>
<%= link_to 'Add New Course', new_grade_course_path(@grade, @course), :class => "button button_orange" %>
<% end %>
</div>
</div>
课程控制器.rb:
class CoursesController < ApplicationController
before_action :set_course, only: [:show, :edit, :update, :destroy]
before_action :set_grade
load_and_authorize_resource
respond_to :html
def index
@grade = Grade.find(params[:grade_id])
@subjects = Subject.all
@courses = @grade.courses.all
# respond_with(@course)
end
.
.
.
def course_params
params.require(:course).permit(:title, :period, :description, :semester, :grade, :grade_id, :video_url, :chapter_id, :subject_id)
end
end
课程.rb:
class Course < ActiveRecord::Base
# TODO: add validations
resourcify
belongs_to :grade
has_many :chapters
has_many :packages
belongs_to :subject
end
主题.rb:
class Subject < ActiveRecord::Base
has_many :courses
end