Ruby模型,我应该选择继承还是仅仅关联

时间:2011-12-01 08:27:23

标签: ruby-on-rails ruby-on-rails-3

我有以下表格和字段

 User   :username,:password,:email

 Organiser  :organiser_specific_fields

 Participant  :participant_specific_fields

组织者和参与者是用户,

用户已经存在于系统中,

当用户组织Party时,我创建Party类的实例,将他添加为该Party的Organizer并将其他用户添加为参与者。

如何在Rails中对此进行建模?考虑到用户已经存在于系统中,我无法弄清楚在Rails中实现这一点的最佳方法是什么。

2 个答案:

答案 0 :(得分:1)

根据您的评论,我建议您坚持使用以下架构:

  1. 用户表,保存有关用户的所有详细信息(名字,姓氏)
  2. 聚会表,其中包含有关聚会的所有详细信息(时间,地点......)
  3. 下面列出的模型的两个连接表:

  4. 此代码未经测试,可能需要对名称进行一些调整:

    class User < ActiveRecord::Base
        has_many :parties, :through => :participations, :source => :user
        has_many :organised, :through => :organises, :source => :user
    end
    
    class Party < ActiveRecord::Base
        has_many :participants, :through => :participations
        has_many :organizers, :through => :organises
    end
    
    class Participation < ActiveRecord::Base
       belongs_to :user
       belongs_to :party
       # this class represents "a user is going to a party"
       # additional fields, which are specific to a participation go here as well
    end
    
    class Organises < ActiveRecord::Base
        belongs_to :user
        belongs_to :party
        # This class represents "user is the organisator of a party"
        # additional fields, which are specific to organizing a party go here
    end
    

    优点:

    • 您无需触摸用户表
    • 一方可以有两个或更多的组织者
    • 党的组织者也可以参加聚会(希望如此)
    • 数据库中没有数据重复

    缺点:

    • 您必须自己管理协会:用户不得两次去同一方(或成为组织者)

    我希望这有助于澄清一些事情。可以在此link的rails文档中找到更多信息。

答案 1 :(得分:0)

取决于每个特定字段的数量以及用户表与这些附加字段的外观有多差。如果组织者和参与者不是数据库中的单独实体,可能他们可能只是混合!

但总的来说,肯定是继承恕我直言。