Skip to content

Commit

Permalink
Add GET /api/choices/new and associated bits
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich Daley authored and stefanha committed Jul 28, 2012
1 parent ff60f18 commit bceab77
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 1 deletion.
12 changes: 12 additions & 0 deletions app/controllers/api/choices_controller.rb
@@ -1,2 +1,14 @@
class Api::ChoicesController < ApplicationController

def new
if !params[:topic]
render :json => {:error => 'no topic supplied'}, :status => :unprocessable_entity
else
render :json => Choice.create_randomly(:topic => params[:topic]).for_api
end
end

def update
end

end
24 changes: 24 additions & 0 deletions app/models/choice.rb
Expand Up @@ -3,4 +3,28 @@ class Choice < ActiveRecord::Base
belongs_to :option_a, :class_name => 'Tweet'
belongs_to :option_b, :class_name => 'Tweet'
# attr_accessible :title, :body

def self.create_randomly(params)
topic = Topic.where(:title => params[:topic]).first!
real = Tweet.where(:topic_id => topic, :fake => false).order("RANDOM()").first
fake = Tweet.where(:topic_id => topic, :fake => true).order("RANDOM()").first

a_b = [real,fake].shuffle
c = Choice.new
c.topic = topic
c.option_a = a_b[0]
c.option_b = a_b[1]
c.save!
c
end

def for_api
{
:id => self.id,
:topic => self.topic.title,
:a => self.option_a.text,
:b => self.option_b.text
}
end

end
2 changes: 2 additions & 0 deletions app/models/topic.rb
Expand Up @@ -3,4 +3,6 @@ class Topic < ActiveRecord::Base
has_many :tweets
has_many :markov_chains
has_many :choices

validates_uniqueness_of :title
end
2 changes: 1 addition & 1 deletion app/models/tweet.rb
@@ -1,4 +1,4 @@
class Tweet < ActiveRecord::Base
belongs_to :topic
attr_accessible :fake, :text
attr_accessible :fake, :text
end

0 comments on commit bceab77

Please sign in to comment.