ruby - How to implement Active Record like 'find' method in Sinatra and Sequel? -
i building simple sinatra app training purposes.
i using sequel gem , don't want use active record.
my files are:
/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 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 |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 # tried this: # # def self.find(params) # data.where(id: params).collect |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 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 '/' @ideas = idea.all haml :index end not_found haml :error end post '/create' idea = idea.new(title: params['idea_name'], description: params['idea_description']) idea.save redirect to('/') end '/edit/:id' @idea = idea.find(params[:id]) @title = "edit form" haml :edit end put ':id' @idea = idea.find(params[:id]) @title = "edit form" haml :edit end
just find
method work when use this:
def self.find(params) record = data[id: params] if record.nil? nil # or raise exception... else self.new(record) end end
but have reimplement features active record has, example kind of persisted?
method check if record present in database , update record instead of creating new one.
with current implementation of save
create new record each time call it. may better if don't set id
let auto_increment
of database handle that.
Comments
Post a Comment