Commit 6eb519b7029aa371d24ac7984fc09e4ae482c82c

Authored by Pius Uzamere
1 parent d66be11a

refactored prompt picking

app/models/choice.rb
@@ -38,7 +38,7 @@ class Choice < ActiveRecord::Base @@ -38,7 +38,7 @@ class Choice < ActiveRecord::Base
38 votes_count || 0 38 votes_count || 0
39 end 39 end
40 40
41 - after_create :generate_prompts 41 + #after_create :generate_prompts
42 def before_create 42 def before_create
43 unless item 43 unless item
44 @item = Item.create!(:creator => creator, :data => data) 44 @item = Item.create!(:creator => creator, :data => data)
app/models/item.rb
@@ -14,4 +14,10 @@ class Item < ActiveRecord::Base @@ -14,4 +14,10 @@ class Item < ActiveRecord::Base
14 14
15 validates_presence_of :creator_id 15 validates_presence_of :creator_id
16 validates_presence_of :data, :on => :create, :message => "can't be blank" 16 validates_presence_of :data, :on => :create, :message => "can't be blank"
  17 +
  18 + def self.mass_insert!(creator_id, data_array)
  19 + #alpha
  20 + inserts = data_array.collect{|i| "(#{connection.quote i}, #{connection.quote creator_id})"}.join(", ")
  21 + connection.insert("INSERT INTO items(data, creator_id) VALUES (#{inserts})")
  22 + end
17 end 23 end
app/models/question.rb
1 class Question < ActiveRecord::Base 1 class Question < ActiveRecord::Base
  2 + require 'set'
2 belongs_to :creator, :class_name => "Visitor", :foreign_key => "creator_id" 3 belongs_to :creator, :class_name => "Visitor", :foreign_key => "creator_id"
3 belongs_to :site, :class_name => "User", :foreign_key => "site_id" 4 belongs_to :site, :class_name => "User", :foreign_key => "site_id"
4 5
@@ -21,11 +22,20 @@ class Question &lt; ActiveRecord::Base @@ -21,11 +22,20 @@ class Question &lt; ActiveRecord::Base
21 choices_count 22 choices_count
22 end 23 end
23 24
24 - def picked_prompt 25 + #TODO: generalize for prompts of rank > 2
  26 + #TODO: add index for rapid finding
  27 + def picked_prompt(rank = 2)
  28 + raise NotImplementedError.new("Sorry, we currently only support pairwise prompts. Rank of the prompt must be 2.") unless rank == 2
  29 + choice_id_array = distinct_array_of_choice_ids(rank)
  30 + @p = prompts.find_or_create_by_left_choice_id_and_right_choice_id(choice_id_array[0], choice_id_array[1])
  31 + end
  32 +
  33 + def distinct_array_of_choice_ids(rank = 2, only_active = true)
25 begin 34 begin
26 - @p = prompts.first(:order => 'RANDOM()', :include => [{ :left_choice => :item }, { :right_choice => :item }])  
27 - end until @p.active?  
28 - return @p 35 + @the_choice_ids = Set.new
  36 + rank.times { @the_choice_ids << choices.active.first(:order => 'RANDOM()', :select => 'id').id }
  37 + end until @the_choice_ids.size == rank
  38 + @the_choice_ids.to_a
29 end 39 end
30 40
31 def picked_prompt_id 41 def picked_prompt_id