數據模型:
在我的理解,這裏是你的數據模型(點擊放大):
Data model http://yuml.me/6afcad62
遷移:
遷移會讓您在遷移級別滿足第二個要求:
class CreateAwards < ActiveRecord::Migration
def self.up
create_table :awards do |t|
# custom attributes here
t.string :name
t.text :description
t.references :user, :null => false
t.references :game_week#, :null => false
t.references :badge, :null => false
t.timestamps
end
# a user can be awarded no more than a badge per week
add_index :awards, [:user_id, :badge_id, :game_week_id], :unique => true
# a user can be awarded no more than a badge for ever
#add_index :awards, [:user_id, :badge_id], :unique => true
end
def self.down
drop_table :awards
end
end
型號:
該模型將讓你滿足你的要求,在模型級別:
class Award < ActiveRecord::Base
validate_uniqueness_of :user, :badge,
:if => Proc.new { |award| award.badge === BadgeA }
validate_uniqueness_of :user, :badge, game_week,
:unless => Proc.new { |award| award.badge === BadgeA }
#validate_uniqueness_of :user, :badge, game_week,
# :if => Proc.new { |award| award.badge === BadgeB }
end
注:
我沒有嘗試這些片段,但我認爲這個想法在這裏:)
===是什麼? – keruilin 2010-05-28 01:55:59
這是Ruby中的case平等運算符。 您可以在[Object Ruby doc] [1]和[博客文章] [2]中看到更多詳細信息。 [1]:http://ruby-doc.org/core/classes/Object.html#M000345 [2]:http://www.pluitsolutions.com/2006/10/09/comparing-equality- EQL相等和 - 區分平等合紅寶石/ – 2010-05-28 07:13:13