Created
May 29, 2012 18:13
-
-
Save chanks/2829829 to your computer and use it in GitHub Desktop.
Sequel nested attributes possible API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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