如何构建包含ActiveResource类的复杂多态关联?

时间:2011-12-09 03:31:21

标签: ruby-on-rails polymorphic-associations activeresource tournament

我正在尝试构建一个多样的tournament management system,它允许多种类型的锦标赛支持后端。目标是为锦标赛支架后端(此处为PlasTournament)提供一个非常简单的选项,并提供多个更精细的后端(现在只有Challonge::Tournament的可能性,来自Challonge },通过challonge-api使用API gem。

我的模特:

class Tournament < ActiveRecord::Base
  belongs_to :event 
  validates :event, :presence => true
  has_one :remote, :as => :tournament_bracket, :dependent => :destroy
end

class PlasTournament < ActiveRecord::Base
  belongs_to :winner, :class_name => "User"
  belongs_to :creator, :class_name => "User"
  belongs_to :tournament_bracket, :polymorphic => true
  has_and_belongs_to_many :participants, :class_name => "User"
end

还有Challonge::Tournament,但我不确定如何让它适应这种风格。我需要monkeypatch吗?它是一个ActiveResource类,我真的只需要在Tournament类的多态关联中存储它的类和id。

我以前有过这些模型:

class Tournament < ActiveRecord::Base
  belongs_to :event 
  validates :event, :presence => true
  has_one :remote_tournament, :as => :tournament_bracket, :dependent => :destroy
end

class RemoteTournament < ActiveRecord::Base
  belongs_to :tournament_bracket, :polymorphic => true

  def tournament_bracket_type_type=(sType)
     super(sType.to_s.classify.constantize.base_class.to_s)
  end
end

class PlasTournament < RemoteTournament
  belongs_to :winner, :class_name => "User"
  belongs_to :creator, :class_name => "User"
  belongs_to :tournament_bracket, :polymorphic => true
  has_and_belongs_to_many :participants, :class_name => "User"
end

或类似的东西。它不起作用,我没有像上面那样提交它。

理想情况下,我希望能够在我的控制器的create方法中执行类似的操作(我知道其中一些可以通过将params[:tournament]传递给#new来处理;我是只是明确这个例子):

@tournament = Tournament.new
@tournament.event = params[:tournament][:event_id]
@tournament.name = params[:tournament][:name]
@remote = params[:tournament][:remote_type].constantize.new
#set its state
@tournament.remote = @remote
@tournament.save!

然后在Tournament#show中执行以下操作:

@tournament = Tournament.find params[:id]
#the only things I need from Tournament are the 
#name, description, max_participants, and remote
@remote = @tournament.remote
#^this is primarily for shorthand access

然后,在视图中,我可以根据remote的类传递给某些部分或小部件。

case remote.class
when PlasTournament
  render :partial => 'brackets/plas'
when Challonge::Tournament
  render :partial => 'brackets/challonge'
end

我是不是在摇杆?这似乎相当简单,但我想我已经陷入了Rails的实现细节。

我正在寻找的是一种将多态比赛包围系统隐藏在锦标赛课程背后的方法。

0 个答案:

没有答案