【发布时间】:2012-03-09 07:55:42
【问题描述】:
我目前正在 Ruby on Rails 3.2.1 中开发 Dungeons & Dragons 4th Edition Character Sheet 应用程序。我目前处于一个阶段,我意识到我需要将角色种族(矮人、精灵……)与能力奖励联系起来。 (例如:矮人作为种族特性在体质和智慧能力上获得 +2 加值。)
我目前有以下设置:
class Character < ActiveRecord::Base {
has_many :attributions
has_many :abilities, through: :attributions
}
class Attribution < ActiveRecord::Base {
belongs_to :character
belongs_to :ability
# The "attributions" table also has the column "score,"
# which is the character's ability score
}
class Ability < ActiveRecord::Base {
has_many :attributions
has_many :characters, through: :attributions
}
如您所见,每个角色都有自己的一套能力。我想我可以为角色竞赛做同样的事情,但我不确定这方面的任何最佳实践。我可能可以使用相同的连接模型,创建类似这样的东西(Character 将保持不变,除了覆盖 abilities 方法,也许):
class CharacterRace < ActiveRecord::Base {
# I am not sure if this will actually work, but I hope
# you understand what I am trying to do with this
has_many :racial_ability_traits, class_name: "Attribution"
has_many :abilities, through: :racial_ability_traits
}
class Attribution < ActiveRecord::Base {
# The following two are just like before
belongs_to :character
belongs_to :ability
# This field would be new
belongs_to :character_class
}
class Ability < ActiveRecord::Base {
# These are the same as above
has_many :attributions
has_many :characters, through: :attributions
# These would be new, and I am not sure if it will work, but
# I hope you understand what I amm trying to do with this
has_many :racial_traits, class_name: "Attribution"
has_many :character_races, through: :racial_ability_traits
}
然而,即使 如果 这可行,我还是觉得为不同的连接使用相同的连接模型(即使目的几乎相同)是一种丑陋的方法。当然,我可以像这样创建不同类型的连接:
class CharacterRace < ActiveRecord::Base {
has_many :abilities, through: :attributions
# These are for the racial bonus
has_many :racial_ability_bonuses
has_many :abilities, through: :racial_ability_bonuses
}
class RacialAbilityBonus < ActiveRecord::Base {
belongs_to :character_race
belongs_to :ability
}
class Ability < ActiveRecord::Base {
has_many :attributions
has_many :abilities, through: :attributions
# These are for the racial bonus
has_many :racial_ability_bonuses
has_many :character_races, through: :racial_ability_bonuses
}
这可能会起作用,但有一个问题。不仅种族可以具有这样的特征/奖励。一件魔法物品也可能提供能力加成。因此,Item 模型也应该被赋予has_many :abilities, through: :item_ability_bonus 关联。继续上面解释的道路,这将导致很多连接模型。
因此,我问你们是否知道处理这个问题的任何好方法。任何关于改进我现有代码的建议也是受欢迎的。
我非常感谢您认真的回答。 :-)
【问题讨论】:
标签: ruby-on-rails activerecord model many-to-many has-many-through