Ruby on Rails的建模策略

时间:2011-03-01 05:29:09

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

我正在尝试为我的应用程序创建最佳建模策略,并且在理解最有效的解决方案时遇到问题。

在顶层我们有游戏玩家。
玩家可以参加很多活动。
活动有很多参与者(谁是游戏玩家)。

活动中可以有任意数量的参与者,这就是让我失望的原因。如果他们是一定数量的参与者,我可以将它们作为事件模型中的列与游戏玩家的外键,但我不知道如何为此设置关联。

我的测试设置如此

rails gen。模特玩家..
rails gen model事件..
rails gen model参与者..事件:参考文献

现在......

活动has_many:参与者
参与者belongs_to:event

我无法弄清楚的问题是如何将参与者链接到他们的玩家行?

我认为它类似于以下内容,但Rails指南中的示例并不完全适合我的示例...

Gamer has_many:event_participants,:through => :事件

2 个答案:

答案 0 :(得分:3)

我会通过一些关系命名更改和连接表来解决这个问题:

class Gamer
    has_many :hosted_events, :class_name => 'Event', :foreign_key => :host_id
    has_and_belongs_to_many :events
end

class Event
    belongs_to :host, :class_name => 'Gamer'
    has_and_belongs_to_many :gamers
end

在您的数据库中,您需要包含events_gamersevent_id列的联接表gamer_id。不过没有模特--Rails将负责幕后的一切。

你真的只需要这两个型号。除非“游戏玩家G参与事件E”的关系需要更多数据(例如,“并带来筹码!”) - 然后它将保证自己的模型(我称之为参与 - 参与者有点误导),并且has_and_belongs_to_many关系将变为has many :through s。

希望这有帮助!

答案 1 :(得分:1)

我会使用Single-Table-Inheritance并按照这样做:

1.在参与者表格中添加“类型”列

2.生成玩家模型并使其继承参与者模型。 (继承)

3.在参与者表格中定义玩家的属性。

4.如下设置模型:

class Event < ActiveRecord::Base
  has_many :registrations
  has_many :participants, :through => :registrations
end

class Participant < ActiveRecord::Base
  has_many :registrations
  has_many :events, :through => :registrations
end

class Gamer < Participant
end

class Registration < ActiveRecord::Base
  belongs_to :event
  belongs_to :participant
end

所以现在你可以做到

gamer = Gamer.first #just an instance
gamer.events
event = Event.first #just an instance
all_participants = event.participants
gamers = event.gamers