Skip to content

Instantly share code, notes, and snippets.

@chanks
Created May 29, 2012 18:13

Revisions

  1. chanks revised this gist May 30, 2012. 1 changed file with 21 additions and 1 deletion.
    22 changes: 21 additions & 1 deletion gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -28,6 +28,8 @@ 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"},
    @@ -37,7 +39,25 @@ q = Question.new :content => "What color is the sky?",

    q.save

    # And then later:
    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"},
  2. chanks created this gist May 29, 2012.
    47 changes: 47 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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

    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

    # And then later:

    q.update :answers_attributes => [
    {:letter => "A", :content => "Bluish"},
    {:letter => "B", :content => "Greenish"},
    {:letter => "C", :content => "Orangish"},
    {:letter => "D", :content => "Yellowish"}
    ]