I'm attempting to design an achievement system in Ruby on Rails and have run into a snag with my design/code.
Attempting to use polymorphic associations:
class Achievement < ActiveRecord::Base
belongs_to :achievable, :polymorphic => true
end
class WeightAchievement < ActiveRecord::Base
has_one :achievement, :as => :achievable
end
Migrations:
class CreateAchievements < ActiveRecord::Migration
... #code
create_table :achievements do |t|
t.string :name
t.text :description
t.references :achievable, :polymorphic => true
t.timestamps
end
create_table :weight_achievements do |t|
t.integer :weight_required
t.references :exercises, :null => false
t.timestamps
end
... #code
end
Then, when I try this following throw-away unit test, it fails because it says that the achievement is null.
test "parent achievement exists" do
weightAchievement = WeightAchievement.find(1)
achievement = weightAchievement.achievement
assert_not_nil achievement
assert_equal 500, weightAchievement.weight_required
assert_equal achievement.name, "Brick House Baby!"
assert_equal achievement.description, "Squat 500 lbs"
end
And my fixtures: achievements.yml...
BrickHouse:
id: 1
name: Brick House
description: Squat 500 lbs
achievable: BrickHouseCriteria (WeightAchievement)
weight_achievements.ym...
BrickHouseCriteria:
id: 1
weight_required: 500
exercises_id: 1
Even though, I can't get this to run, maybe in the grand scheme of things, it's a bad design issue. What I'm attempting to do is have a single table with all the achievements and their base information (name and description). Using that table and polymorphic associations, I want to link to other tables that will contain the criteria for completing that achievement, e.g. the WeightAchievement table will have the weight required and exercise id. Then, a user's progress will be stored in a UserProgress model, where it links to the actual Achievement (as opposed to WeightAchievement).
The reason I need the criteria in separate tables is because the criteria will vary wildly between different types of achievements and will be added dynamically afterwards, which is why I'm not creating a separate model for each achievement.
Does this even make sense? Should I just merge the Achievement table with the specific type of achievement like WeightAchievement (so the table is name, description, weight_required, exercise_id), then when a user queries the achievements, in my code I simply search all the achievements? (e.g. WeightAchievement, EnduranceAchievement, RepAchievement, etc)