开发者

Ruby on Rails: multiple acts_as_list directives for the same parent-child pair

I am developing a card game server, for a game where each player has a deck and a discard pile. To reflect the fact that a given card could be located in a player's deck or their discard pile, I have my Player model set up as follows:

class Player < ActiveRecord::Base
  belongs_to :game

  has_many :deck_cards, :class_name => "Card",
                        :conditions => "location = 'deck'",
                    开发者_JS百科    :order => "position",
                        :dependent => :delete_all

  has_many :discard_cards, :class_name => "Card",
                           :conditions => "location = 'discard'",
                           :order => "position",
                           :dependent => :delete_all
end

Is it possible to define my Card model in such a way that I can have it acts_as_list with each card in exactly one list (either deck or discard for a single player)?


Your problem is not validations, its more that acts_as_list will not allow more than list over a single belongs_to relationship.

This following validation will ensure that a card is in either a player's discard or deck list but not both.

validates_uniqueness_of [:fields, :that, :uniquely, :describe, :a, :card],
  :scope => [:player_id, :location]

You should be able to use STI to achieve the multiple lists you desire. Note: this is untested but should at least put you on the right track.

class Card < ActiveRecord::Base
  belongs_to :player
  validates_uniqueness_of [:fields, :that, :uniquely, :describe, :a, :card],
    :scope => [:player_id, :location]
  set_inheritance_column :location
end

class DeckCard < Card
  acts_as_list, :scope => :player
end

class DiscardCard < Card
  acts_as_list, :scope => :player
end

class Player
  belongs_to :game
  has_many :deck_cards, :order => "position",
                        :dependent => :delete_all

  has_many :discard_cards, :order => "position",
                           :dependent => :delete_all
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜