【问题标题】:Rails. Multiple instances of same foreign key in a single table导轨。单个表中相同外键的多个实例
【发布时间】:2015-10-29 12:39:16
【问题描述】:

我不确定如何为以下需求建模:

我们向用户发送一包 3 种不同的啤酒。用户分为 4 类品尝档案。然后,我们为所有用户准备了 4 包不同的啤酒。然后用户对啤酒进行评分,这将定期发生。

注意:我主要担心的是我有一个表(包)可能有多个相同外键的实例。每包包含 3 种啤酒。

目前我有以下型号:

用户/啤酒/个人资料/包装/评分

class User < ActiveRecord::Base
  belongs_to :profile 
  has_many :ratings # A user rates every beer received.
  has_many :beers, through: :ratings
end

class Beer < ActiveRecord::Base
  has_many :ratings
  has_many :users, through: :ratings
  has_many :packs
end

class Profile < ActiveRecord::Base
  has_many :packs #we setup and send periodic packs for each tasting_profile (Profile)
  has_many :users #each tasting profile has many users
  has_may :beers #each tasting profile has many possible beers
end

class Pack < ActiveRecord::Base
  belongs_to :beer #Not sure
  belongs_to :profile
end

class Rating < ActiveRecord::Base
  belongs_to :user
  belongs_to :beer
end

包装模型问题: 我的第一个选择是在 Pack 模型中包含以下字段:

  1. pack_id
  2. profile_id (FK)
  3. beer_id (FK1)
  4. beer_id (FK2)
  5. beer_ip (FK3)
  6. delivery_month

这样我就有一个完整的包可以进入。

在这里研究我读到这显然是一种不好的做法,只建议使用一个 FK 作为入口。像这样的:

  1. pack_id
  2. profile_id (FK)
  3. beer_id (FK)
  4. delivery_month

在这种情况下,每个包我会有 3 个条目。

最后我在考虑研究一个数组字段(不确定是否可以用外键完成):

  1. pack_id
  2. profile_id (FK)
  3. beers [beer_id1 , beer_id2, beer_id3] # 或哈希 [beer_1: beer_id, beer_2:..]
  4. delivery_month

创建包后,我需要根据用户数量在评级表中填充所需数量的以下条目。如果我有 100 个用户在品尝个人资料中,我会将 3 个啤酒包发送给他们,导致这里有 300 个条目

  1. rating_id
  2. User_id (FK)
  3. beer_id (FK)
  4. 交货日期

我真的很困惑如何正确建模。 ¡ 我会感谢任何可能的帮助!我试图尽可能详细。如果您需要进一步说明,请告诉我。

¡¡提前致谢!!

【问题讨论】:

    标签: ruby-on-rails database-design rails-models


    【解决方案1】:

    这花了我很多时间,但比预期的要简单。只要我在同一个表中需要多个相同的 foreign_id 实例,就应该清楚我需要另一个连接表。

    首先我尝试使用 has_and_belongs_to_many 关联,但在删除连接表中的“关联”条目时遇到问题。所以我以 has_many 低谷结束。这些是变化:

    class Beer < ActiveRecord::Base
      has_many :pack_details
      has_many :packs through: :pack_details
      ...
    end
    
    class Pack < ActiveRecord::Base
      has_many :pack_details, dependent: destroy
      has_many _beers, through: : pack_details
      accepts_nested_attributes_for :pack_details, allow_destroy => true
      ...
    end
    
    class PackDetail < ActiveRecord::Base
      Belongs_to :pack
      Belongs_to :beer
      ...
    end
    

    一切正常!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 2018-12-04
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      相关资源
      最近更新 更多