rating.rb
class Rating < ActiveRecord::Base
belongs_to :vote
belongs_to :student
belongs_to :course_textbook
validates_presence_of :vote, :student
end
course_textbook.rb
class CourseTextbook < ActiveRecord::Base
belongs_to :course
belongs_to :textbook
has_many :ratings
validates_presence_of :course, :textbook
end
有没有办法代替rating.course_textbook.textbook
你去rating.textbook
?我会在模型中制作方法吗?或者有没有办法让ActiveRecord这样做?
由于
答案 0 :(得分:1)
您可以通过代表团实现这一目标:
class Rating < ActiveRecord::Base
...
delegate :textbook, to: :course_textbook
end
现在你可以这样称呼它:
rating.textbook
您可以在此处找到delegate
- 方法的更多选项:http://guides.rubyonrails.org/active_support_core_extensions.html#method-delegation