Skip to content

Instantly share code, notes, and snippets.

@georgekettle
Last active December 24, 2020 02:08
Show Gist options
  • Save georgekettle/16058cbdd0cd321885944264f9a8e245 to your computer and use it in GitHub Desktop.
Save georgekettle/16058cbdd0cd321885944264f9a8e245 to your computer and use it in GitHub Desktop.
Livecode: Active Record Basics (Batch 466)
# migrate/20201223190654_create_questions.rb
class CreateQuestions < ActiveRecord::Migration[6.0]
def change
create_table :questions do |t|
t.string :question
t.string :option_a
t.string :option_b
t.timestamps # add 2 columns, `created_at` and `updated_at`
end
end
end
# db/migrate/20201223191214_create_answers.rb
class CreateAnswers < ActiveRecord::Migration[6.0]
def change
create_table :answers do |t|
t.string :letter
t.references :question, index: true
t.timestamps # add 2 columns, `created_at` and `updated_at`
end
end
end
# models/answer.rb
class Answer < ActiveRecord::Base
belongs_to :question
end
require_relative "config/application"
require "sinatra"
require "sinatra/reloader"
require "sinatra/activerecord"
get "/" do
@questions = Question.all
erb :index
end
post "/questions" do
# params accesible as hash when request sent: {"question"=>"", "option_a"=>"", "option_b"=>"", "answer"=>""}
q = Question.create!(
question: params["question"],
option_a: params["option_a"],
option_b: params["option_b"],
)
Answer.create!(
question_id: q.id,
letter: params["answer"]
)
redirect '/'
end
<!-- views/index.erb -->
<h1><%= "Questions" %></h1>
<ul>
<% @questions.each do |question| %>
<li style="list-style: none;">
<div style="padding: 20px; border-radius: 20px; background-color: 'white'; box-shadow: 0px 2px 10px rgba(0,0,0,0.2); margin-bottom: 10px">
<h3><%= question.question %></h3>
<h4>a) <%= question.option_a %></h4>
<h4>b) <%= question.option_b %></h4>
<% if question.answer %>
<h3>Has answer!</h3>
<% end %>
</div>
</li>
<% end %>
</ul>
<form action="/questions" method="post">
<label for="question">Question</label>
<input type="text" name="question">
<label for="option_a">Option A</label>
<input type="text" name="option_a">
<label for="option_b">Option B</label>
<input type="text" name="option_b">
<label for="answer">Answer</label>
<input type="text" name="answer">
<input type="submit">
</form>
# models/question.rb
class Question < ActiveRecord::Base
has_one :answer
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment