has_many通过:四层?

时间:2018-08-11 10:04:27

标签: ruby-on-rails ruby ruby-on-rails-5

您如何管理四层模型连接?

所以我有一个Group(小组),它具有许多类别,具有许多考试,具有许多主题。

class Group < ApplicationRecord
   has_many :categories
   has_many :exams, through: :categories
   #has_many :topics, through :exams
   accepts_nested_attributes_for :categories
end

class Category < ApplicationRecord
  belongs_to :group
  has_many :exams
end

class Exam < ApplicationRecord
  belongs_to :category
  has_many :topics
  has_one :group, through: :category
  accepts_nested_attributes_for :topics
end

class Topic < ApplicationRecord
  belongs_to :exam
  has_one :category, through: :exam
  #has_one :group, through :category
end

在中间有两个表的情况下,如何正确地将Group through连接到Topic?

(为清楚起见而编辑)

1 个答案:

答案 0 :(得分:3)

  

我想念什么?还是只有四层是荒谬的?

不荒谬。只需照常提供 <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/bookCoverDrawee" android:layout_width="56dp" android:layout_height="67dp" android:layout_alignParentEnd="true" android:layout_alignTop="@+id/bookTitleTxt" android:paddingStart="8dp" fresco:placeholderImage="@android:drawable/ic_menu_close_clear_cancel" /> has_many关联:

through

这将生成一个SQL,类似于:

class Group < ApplicationRecord
  has_many :categories
  has_many :exams, through: :categories
  has_many :topics, through: :exams
end