Skip to content

Instantly share code, notes, and snippets.

@chanks
Created May 29, 2012 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chanks/2829829 to your computer and use it in GitHub Desktop.
Save chanks/2829829 to your computer and use it in GitHub Desktop.
Sequel nested attributes possible API
require 'rubygems'
require 'sequel'
DB = Sequel.sqlite
DB.create_table :questions do
primary_key :id
String :content
end
DB.create_table :answers do
Integer :question_id
String :letter
String :content
primary_key [:question_id, :letter]
foreign_key [:question_id], :questions
end
Sequel::Model.plugin :nested_attributes
class Question < Sequel::Model
one_to_many :answers
nested_attributes :answers, :new_pk => :create
end
class Answer < Sequel::Model
unrestrict_primary_key
end
# Current supported API:
q = Question.new :content => "What color is the sky?",
:answers_attributes => [
{:letter => "A", :content => "Blue"},
{:letter => "B", :content => "Green"},
{:letter => "C", :content => "Orange"}
]
q.save
q.update :answers_attributes => [
{:question_id => q.id, :letter => "A", :content => "Bluish"},
{:question_id => q.id, :letter => "B", :content => "Greenish"},
{:question_id => q.id, :letter => "C", :content => "Orangish"},
{:question_id => q.id, :letter => "D", :content => "Yellowish"}
]
# Ideal API:
q = Question.new :content => "What color is the sky?",
:answers_attributes => [
{:letter => "A", :content => "Blue"},
{:letter => "B", :content => "Green"},
{:letter => "C", :content => "Orange"}
]
q.save
q.update :answers_attributes => [
{:letter => "A", :content => "Bluish"},
{:letter => "B", :content => "Greenish"},
{:letter => "C", :content => "Orangish"},
{:letter => "D", :content => "Yellowish"}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment