经常会遇到这种情况
study_record.lesson.name
study_record.course_package.name
可以采用委托实现更优美的代码:
class StudyRecord < ActiveRecord::Base belongs_to :user belongs_to :lesson belongs_to :course_package delegate :name, :to => :lesson, :prefix => true delegate :name, :to => :course_package, :prefix => true end
<%= study_record.lesson_name%> <%= study_record.course_package_name%>