Rails-has_one:through和has_many:through

时间:2018-09-29 02:36:56

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

我想设计一个俱乐部系统。俱乐部有许多用户,一个用户有一个俱乐部,以及存储一些信息的成员资格。 我可以使用has_one:through和has_many:through建立一对多关联吗?

class Club < ApplicationRecord
  has_many :users, through: :memberships
  has_many :memberships
end

class Membership < ApplicationRecord
  belongs_to :club
  belongs_to :user
end

class User < ApplicationRecord
  has_one :club, through: :membership
  has_one :membership
end

因为在Rails指南中,它提到has_one:through建立一对一的关联,并提到has_many:through建立多对多的关联。 我可以用这种方式吗?谢谢。

1 个答案:

答案 0 :(得分:0)

可以。您必须先调整模型以定义through部分,然后再定义另一个通过它的关联,即

class Club < ApplicationRecord
  has_many :memberships
  has_many :users, through: :memberships
end

class User < ApplicationRecord
  has_one :membership
  has_one :club, through: :membership
end