【问题标题】:Rails - has_one :through and has_many :throughRails - has_one :through 和 has_many :through
【发布时间】:2019-03-04 23:57:02
【问题描述】:

我想设计一个俱乐部系统。一个俱乐部有很多用户,一个用户有一个俱乐部,还有一个存储一些信息的会员资格。 我可以使用 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 建立多对多的关联。 我可以用这种方式吗?谢谢。

【问题讨论】:

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


    【解决方案1】:

    你可以。在定义另一个通过它的关联之前,您必须稍微调整模型以定义您的 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
    

    【讨论】:

    • 感谢您的帮助!我困惑了很久。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    相关资源
    最近更新 更多