与has_many一起苦苦挣扎:通过

时间:2013-12-09 18:46:53

标签: ruby-on-rails foreign-keys associations

假设我有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_idlesson_id字段。)

我如何制作它以便调用@user.points会将条目数量返回到Progress表中。另外,我将如何建立关系?

2 个答案:

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