From 6eb519b7029aa371d24ac7984fc09e4ae482c82c Mon Sep 17 00:00:00 2001 From: Pius Uzamere Date: Fri, 18 Dec 2009 11:49:56 -0500 Subject: [PATCH] refactored prompt picking --- app/models/choice.rb | 2 +- app/models/item.rb | 6 ++++++ app/models/question.rb | 18 ++++++++++++++---- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/app/models/choice.rb b/app/models/choice.rb index 5d35be4..32a64b2 100644 --- a/app/models/choice.rb +++ b/app/models/choice.rb @@ -38,7 +38,7 @@ class Choice < ActiveRecord::Base votes_count || 0 end - after_create :generate_prompts + #after_create :generate_prompts def before_create unless item @item = Item.create!(:creator => creator, :data => data) diff --git a/app/models/item.rb b/app/models/item.rb index 8435e73..75e4e7b 100644 --- a/app/models/item.rb +++ b/app/models/item.rb @@ -14,4 +14,10 @@ class Item < ActiveRecord::Base validates_presence_of :creator_id validates_presence_of :data, :on => :create, :message => "can't be blank" + + def self.mass_insert!(creator_id, data_array) + #alpha + inserts = data_array.collect{|i| "(#{connection.quote i}, #{connection.quote creator_id})"}.join(", ") + connection.insert("INSERT INTO items(data, creator_id) VALUES (#{inserts})") + end end diff --git a/app/models/question.rb b/app/models/question.rb index aafee5d..dac4d03 100644 --- a/app/models/question.rb +++ b/app/models/question.rb @@ -1,4 +1,5 @@ class Question < ActiveRecord::Base + require 'set' belongs_to :creator, :class_name => "Visitor", :foreign_key => "creator_id" belongs_to :site, :class_name => "User", :foreign_key => "site_id" @@ -21,11 +22,20 @@ class Question < ActiveRecord::Base choices_count end - def picked_prompt + #TODO: generalize for prompts of rank > 2 + #TODO: add index for rapid finding + def picked_prompt(rank = 2) + raise NotImplementedError.new("Sorry, we currently only support pairwise prompts. Rank of the prompt must be 2.") unless rank == 2 + choice_id_array = distinct_array_of_choice_ids(rank) + @p = prompts.find_or_create_by_left_choice_id_and_right_choice_id(choice_id_array[0], choice_id_array[1]) + end + + def distinct_array_of_choice_ids(rank = 2, only_active = true) begin - @p = prompts.first(:order => 'RANDOM()', :include => [{ :left_choice => :item }, { :right_choice => :item }]) - end until @p.active? - return @p + @the_choice_ids = Set.new + rank.times { @the_choice_ids << choices.active.first(:order => 'RANDOM()', :select => 'id').id } + end until @the_choice_ids.size == rank + @the_choice_ids.to_a end def picked_prompt_id -- libgit2 0.21.2