2013-04-04 67 views
0

我正在爲訓練目的構建一個簡單的Sinatra應用程序。如何在Sinatra和Sequel中實現Active Record,如'find'方法?

我使用續集寶石,不想使用活動記錄。

我的文件有:

/models/idea.rb:

class Idea 
    attr_reader :id, :title, :description 

    def initialize(input) 
    @id = input[:id] 
    @title = input[:title] 
    @description = input[:description] 
    end 

    def save 
    Idea.data.insert(title: title, description: description) 
    end 

    def self.create_table 
    database.create_table? :ideas do 
     primary_key :id 
     String :title, size: 25 
     Text :description 
    end 
    end 

    def self.data 
    verify_table_exists 
    database[:ideas] 
    end 

    def self.database 
    @database ||= Sequel.sqlite('./db/idea_box.sqlite3') 
    end 

    def self.all 
    data.order(Sequel.desc(:id)).collect do |row| 
     Idea.new(row) 
    end 
    end 

    def self.verify_table_exists 
    @table_exists ||= (create_table || true) 
    end 

    def self.find(params) 
    data.where(id: params) 
    end 
# I also tried this: 
# 
# def self.find(params) 
# data.where(id: params).collect do |row| 
#  Idea.new(row) 
# end 
# end 

    end 
end 

/views/edit.haml:

%h1 Edit idea 
%form{action:"/#{@idea.id}", method: "post"} 
    %input{type: "hidden", name: "_method", value: "put"} 
    %input{type: "text", name: "idea_name", value: "#{@idea.title}"} 
    %br 
    %textarea{name: "idea_description", value: "#{@idea.description}"} 
    %br 
    %input{type: "submit", value: "Submit"} 

application.rb中:

require './models/idea' 


Bundler.require 

helpers do 
    def title 
    if @title 
     "#{@tile} -- IdeaBox" 
    else 
     "IdeaBox" 
    end 
    end 

    def delete_idea_button(idea_id) 
    haml :_delete_idea_button, locals: {idea_id: idea_id} 
    end 
end 



get '/' do 
    @ideas = Idea.all 
    haml :index 
end 

not_found do 
    haml :error 
end 

post '/create' do 


    idea = Idea.new(title: params['idea_name'], description: params['idea_description']) 
    idea.save 

    redirect to('/') 
end 

get '/edit/:id' do 
    @idea = Idea.find(params[:id]) 
    @title = "Edit form" 
    haml :edit 
end 

put ':id' do 
    @idea = Idea.find(params[:id]) 
    @title = "Edit form" 
    haml :edit 
end 

回答

1

只要find方法將工作w母雞你使用這樣的:

def self.find(params) 
    record = data[id: params] 
    if record.nil? 
    nil 
    # or raise an exception... 
    else 
    self.new(record) 
    end 
end 

但你也必須重新實現活動記錄已經有一些特點,例如某種persisted?方法來檢查該記錄是否已經存在於數據庫中,並更新記錄而不是創建一個新的。

隨着您目前的執行save,它會在您每次打電話時創建一條新記錄。如果您自己不設置id,但讓數據庫的auto_increment可以處理該問題,也可能會更好。

相關問題