在belongs_to關係中有沒有辦法使用through
選項? Rails documentation on belongs_to沒有提及through
作爲選項,爲什麼不呢?我想要做的東西像下面這樣:在belongs_to ActiveRecord協會上使用選項
class Lesson < ActiveRecord::Base
attr_accessible :name, :lesson_group_id
belongs_to :lesson_group
belongs_to :level, through: :lesson_group
end
class LessonGroup < ActiveRecord::Base
attr_accessible :name, :level_id
belongs_to :level
has_many :lessons
end
class Level < ActiveRecord::Base
attr_accessible :number
has_many :lesson_groups
end
然後,我可以做這樣的事情Lesson.first.level
。使用最新的穩定Rails(截至目前的3.2.9)。
@MrYoshiji - 在'has_one',Rails的文檔中說,「如果其他類包含的外鍵,才應使用這種方法。如果當前類包含外鍵,那麼你應該使用belongs_to來代替。「 –
'has_one'的文檔還會顯示「選項:[...] - :通過 指定一個連接模型,通過該連接模型執行查詢,因爲:關聯使用:class_name,:primary_key和:foreign_key的選項將被忽略源反射,只能通過連接模型上的has_one或belongs_to關聯使用a:through查詢。「 – MrYoshiji