假设我有3个这样的模型(不确定这是否正确):
class User < ActiveRecord::Base
has_many :lessons
has_many :points, through: :progress
end
class Progress < ActiveRecord::Base
belongs_to :user
has_many :lessons
end
class Lesson < ActiveRecord::Base
belongs_to :progress
end
(进度表包含user_id
和lesson_id
字段。)
我如何制作它以便调用@user.points
会将条目数量返回到Progress
表中。另外,我将如何建立关系?
答案 0 :(得分:0)
class User < ActiveRecord::Base
has_many :progresses
has_many :lessons, through: :progresses
end
class Progress < ActiveRecord::Base
belongs_to :user
belongs_to :lesson
end
class Lesson < ActiveRecord::Base
has_many :progresses
end
答案 1 :(得分:0)
首先,您需要在progress
模型上设置User
的关联,以便through
关联有效:
class User < ActiveRecord::Base
has_many :lessons
has_many :progress
has_many :points, through: :progress
end
然后,您需要在points
表上定义Progress
的方法(或关系)。或者,如果您只想要记录计数,则可以执行:@user.points.size