【问题标题】:How should these Rails Models be associated?这些 Rails 模型应该如何关联?
【发布时间】:2017-03-23 06:24:44
【问题描述】:

我已经想太多了,以至于我现在才感到困惑。

我有一个带有以下模型的 Rails 应用程序:User、Site、Tutorial、TutorialStep。

一个用户可以创建许多教程,每个教程都有一个站点,每个教程都有很多教程步骤。

我遇到问题的模型是 Site。

一个用户有很多教程,并且有很多教程步骤。一个教程属于一个用户,有很多教程步骤,最后一个教程步骤属于一个教程。

现在网站应该属于用户和教程,还是只是教程?

【问题讨论】:

    标签: ruby-on-rails ruby model-associations rails-models


    【解决方案1】:

    我将按如下方式构建关系:

    class User < ApplicationRecord
      has_many :tutorials
      has_many :sites, through: :tutorials
      ...
    end
    
    class Site < ApplicationRecord
      has_many :tutorials
      has_many :users, through: :tutorials
      ...
    end
    
    class Tutorial < ApplicationRecord
      has_many :tutorial_steps
      belongs_to :user
      belongs_to :site
      ...
    end
    
    class TutorialStep < ApplicationRecord
      belongs_to :tutorial
      ...
    end
    

    使Site 属于User 将该站点仅绑定到单个用户,这意味着多个用户不能将教程放在同一个站点上,您必须在同一个站点上重复输入能够实现这一点,在我看来这不是很好的模型设计,因为如果在现实生活中,多个用户在同一个站点上有不同的教程,你希望能够在你的模型和数据中反映相同的行为。因此,如果您希望能够从 User 引用站点,并从 Site 引用用户,我建议在链接它们的表上使用 has many through 关系,即教程表,就像我展示的那样以上。

    【讨论】:

    • 谢谢!这很有意义。其他答案与此接近,但缺少Site 上的has_many :users, through: :tutorials。根据您的观点,这很重要,因为这样我就可以参考用户的网站。
    【解决方案2】:

    用户

    has_many :tutorials
    

    网站

    has_many :tutorials
    

    教程

    has_many :tutorial_steps
    belongs_to :user
    belongs_to :site
    

    教程需要站点 ID 和用户 ID 才能正确地将关联映射到用户和站点

    教程表(... user_id,site_id)

    【讨论】:

    • 您如何看待 John 在上面使用用户和网站的 has_many through 关系的答案?
    【解决方案3】:

    应该是这样的,

    用户.rb

    has_many :tutorials
    has_many :tutorial_steps, through: :tutorials
    

    网站.rb

    has_many :tutorials
    

    教程.rb

    has_many :tutorial_steps
    belongs_to :user
    belongs_to :site
    

    tutorial_step.rb

    belongs_to :tutorial
    has_one :user, through: :tutorial
    has_one :site, through: :tutorial
    

    希望有帮助!

    【讨论】:

    • 感谢您的意见! John 的回答几乎是这样,但还在 Site 模型上添加了has_many :users, through: tutorials,反之亦然在 User 模型上。他的观点是,这样您就可以从User 引用站点。您对此有何看法?
    【解决方案4】:

    据我了解,您可以使用has_one 关系。

    has_one :指定与另一个类的一对一关联

    您可以创建与网站和教程的 has_one 关系

    app/models/user.rb

    has_many :tutorials,->{ includes :site}
    has_many :tutorial_steps, through: :tutorials
    

    包括eager loading 技术,可让您获取网站以及教程关系

    app/models/tutorial.rb

    belongs_to :site
    belongs_to :user
    has_many :tutorial_steps
    

    app/models/site.rb

      has_one :tutorial
    

    app/models/tutorial_step.rb

    belongs_to :tutorial
    

    【讨论】:

    • 感谢 Vishal 的输入,但是一对一的关系在这里不起作用,因为即使一个教程有一个站点,一个站点也可以有很多教程。我应该说得更清楚,谢谢。
    • 在这种情况下,您可以使用@john 帖子。很高兴您找到了解决方案。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    相关资源
    最近更新 更多