Ruby on Rails - 访问引用的连接表的对象

时间:2013-12-21 07:34:34

标签: ruby-on-rails ruby

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这样做?

由于

1 个答案:

答案 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