Sequel::Model Example チュートリアル

http://route477.net/ramaze/?Sequel
http://route477.net/ramaze/?Tutorial

http://d.hatena.ne.jp/uzuki05/20081101/1225535468
http://d.hatena.ne.jp/shibason/20100304/1267697379

http://pastebin.com/uriGCi3D


class Questionnary < Sequel::Model
set_schema do
#system
primary_key :id
time :published
time :updated
#entries
varchar :title
end

one_to_many :questions, :class => 'Question'

before_save{ self.updated = Time.now }
before_create{ self.published = Time.now }

validations.clear

validates do
title_range = 3..255
length_of :title, :within => title_range, :message => "must contain from #{title_range.first.to_s} to #{title_range.end.to_s} caracters"
end

def create(hash)
self[:title] = hash.delete(:title)
save
add_question(Question.new(hash))
self
end

end

class Question < Sequel::Model
set_schema do
primary_key :id
foreign_key :questionnary_id, :empty => false
time :published
time :updated
varchar :question
# type : O,C,M, open(ouverte), close(fermée), multiple(QCM)
varchar :type, :fixed => true, :size => 1
text :answer
end

many_to_one :questionnary, :class => 'Questionnary'
many_to_many :tags, :class => 'Tag'
one_to_many :answers, :class => 'Answer'

before_save{ self.updated = Time.now }
before_create{ self.published = Time.now }

validations.clear

validates do
question_range = 3..255
answer_min = 2
length_of :question, :within => question_range, :message => "must contain from #{question_range.first.to_s} to #{question_range.end.to_s} caracters"
length_of :answer, :minimum => answer_min, :message => "must contain at least #{answer_min.to_s} caracters"
end

def update(hash)
p 'hash :'
p hash
self[:question] = hash[:question]
self[:type] = hash[:type]
self[:answer] = hash[:answer]
# hash.each do |&key|
# self[key] = hash[key] unless self[key].nil?
# end
save
self
end

end

class Answer < Sequel::Model
set_schema do
#system
primary_key :id
foreign_key :question_id
#entries
text :content
Fixnum :is_true, :size => 1 #TODO : boolean
end
many_to_one :question, :class => 'Question'

validations.clear

validates do
content_min = 2
length_of :content, :minimum => content_min, :message => "must contain at least #{content_min.to_s} caracters"
end
end