Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1042319
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T15:29:22+00:00 2026-05-16T15:29:22+00:00

I’m attempting to design an achievement system in Ruby on Rails and have run

  • 0

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)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T15:29:23+00:00Added an answer on May 16, 2026 at 3:29 pm

    The way achievement systems generally work is that there are a large number of various achievements that can be triggered, and there’s a set of triggers that can be used to test wether or not an achievement should be triggered.

    Using a polymorphic association is probably a bad idea because loading in all the achievements to run through and test them all could end up being a complicated exercise. There’s also the fact that you’ll have to figure out how to express the success or failure conditions in some kind of table, but in a lot of cases you might end up with a definition that does not map so neatly. You might end up having sixty different tables to represent all the different kinds of triggers and that sounds like a nightmare to maintain.

    An alternative approach would be to define your achievements in terms of name, value and so on, and have a constant table which acts as a key/value store.

    Here’s a sample migration:

    create_table :achievements do |t|
      t.string :name
      t.integer :points
      t.text :proc
    end
    
    create_table :trigger_constants do |t|
      t.string :key
      t.integer :val
    end
    
    create_table :user_achievements do |t|
      t.integer :user_id
      t.integer :achievement_id
    end
    

    The achievements.proc column contains the Ruby code you evaluate to determine if the achievement should be triggered or not. Typically this gets loaded in, wrapped, and ends up as a utility method you can call:

    class Achievement < ActiveRecord::Base
      def proc
        @proc ||= eval("Proc.new { |user| #{read_attribute(:proc)} }")
      rescue
        nil # You might want to raise here, rescue in ApplicationController
      end
    
      def triggered_for_user?(user)
        # Double-negation returns true/false only, not nil
        proc and !!proc.call(user)
      rescue
        nil # You might want to raise here, rescue in ApplicationController
      end
    end
    

    The TriggerConstant class defines various parameters you can tweak:

    class TriggerConstant < ActiveRecord::Base
      def self.[](key)
        # Make a direct SQL call here to avoid the overhead of a model
        # that will be immediately discarded anyway. You can use
        # ActiveSupport::Memoizable.memoize to cache this if desired.
        connection.select_value(sanitize_sql(["SELECT val FROM `#{table_name}` WHERE key=?", key.to_s ]))
      end
    end
    

    Having the raw Ruby code in your DB means that it is easier to adjust the rules on the fly without having to redeploy the application, but this might make testing more difficult.

    A sample proc might look like:

    user.max_weight_lifted > TriggerConstant[:brickhouse_weight_required]
    

    If you want to simplify your rules, you might create something that expands $brickhouse_weight_required into TriggerConstant[:brickhouse_weight_required] automatically. That would make it more readable by non-technical people.

    To avoid putting the code in your DB, which some people may find to be in bad taste, you will have to define these procedures independently in some bulk procedure file, and pass in the various tuning parameters by some kind of definition. This approach would look like:

    module TriggerConditions
      def max_weight_lifted(user, options)
        user.max_weight_lifted > options[:weight_required]
      end
    end
    

    Adjust the Achievement table so that it stores information on what options to pass in:

    create_table :achievements do |t|
      t.string :name
      t.integer :points
      t.string :trigger_type
      t.text :trigger_options
    end
    

    In this case trigger_options is a mapping table that is stored serialized. An example might be:

    { :weight_required => :brickhouse_weight_required }
    

    Combining this you get a somewhat simplified, less eval happy outcome:

    class Achievement < ActiveRecord::Base
      serialize :trigger_options
    
      # Import the conditions which are defined in a separate module
      # to avoid cluttering up this file.
      include TriggerConditions
    
      def triggered_for_user?(user)
        # Convert the options into actual values by converting
        # the values into the equivalent values from `TriggerConstant`
        options = trigger_options.inject({ }) do |h, (k, v)|
          h[k] = TriggerConstant[v]
          h
        end
    
        # Return the result of the evaluation with these options
        !!send(trigger_type, user, options)
      rescue
        nil # You might want to raise here, rescue in ApplicationController
      end
    end
    

    You’ll often have to strobe through a whole pile of Achievement records to see if they’ve been achieved unless you have a mapping table that can define, in loose terms, what kind of records the triggers test. A more robust implementation of this system would allow you to define specific classes to observe for each Achievement, but this basic approach should at least serve as a foundation.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I have a French site that I want to parse, but am running into
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is
I have a jquery bug and I've been looking for hours now, I can't
I want use html5's new tag to play a wav file (currently only supported
I am currently running into a problem where an element is coming back from

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.