如何在Sinatra和Sequel中实现像'find'方法的Active Record?

时间:2013-04-04 18:52:06

标签: ruby sinatra sequel

我正在构建一个简单的Sinatra应用程序用于培训目的。

我正在使用Sequel gem并且不想使用Active Record。

我的档案是:

/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 个答案:

答案 0 :(得分:1)

当你使用这样的东西时,只需find方法就可以了:

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

但是您还必须重新实现Active Record已有的一些功能,例如某种persisted?方法来检查记录是否已存在于数据库中并更新记录而不是创建新记录。

使用当前的save实现,每次调用它时都会创建一条新记录。如果你自己没有设置id但是让数据库的auto_increment处理它也可能会更好。