[英]Rails - has_one :through and has_many :through
I want to design a club system. 我想设计一个俱乐部系统。 A club has many users, a user has one club, and a membership to store some info. 俱乐部有许多用户,一个用户有一个俱乐部,以及存储一些信息的成员资格。 Can I use has_one :through and has_many :through to build one-to-many associations? 我可以使用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
Because in the Rails Guides, it mentions has_one :through to build one-to-one association, and has_many :through to build many-to-many association. 因为在《 Rails指南》中,它提到has_one:through建立一对一的关联,并提到has_many:through建立多对多的关联。 Can I use this way? 我可以用这种方式吗? Thanks. 谢谢。
You can. 您可以。 You have to adjust your models a bit to define your through
part before defining another association that goes through it, ie 您必须先调整模型以定义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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.