views:

1706

answers:

2

As I understand it, the Sinatra framework, unlike Rails, does not provide an ORM. In that case, how do you talk to a DB in a Sinatra app? Or is Sinatra only for apps that don't use a DB?

+7  A: 

If you like ActiveRecord, use that. Or something else. Datamapper, for instance. For AR with SQLite, this works:

require 'rubygems' # may not be needed, depending on platform
require 'sinatra'
require 'activerecord'

class Article < ActiveRecord::Base
end

get '/' do
  Article.establish_connection(
    :adapter => "sqlite3",
    :database => "hw.db"
  )
  Article.first.title
end
Mike Woodhouse
+18  A: 

If you're using Sinatra, I can't recommend DataMapper highly enough. I have a couple Rails apps where I'm stuck with ActiveRecord, and I'm constantly cursing its shortcomings and design flaws. If you're on Sinatra, DataMapper is a very practical choice.

require "rubygems"
require "sinatra"
require "datamapper"

DataMapper.setup(:default, "sqlite3::memory:")

class Post
  include DataMapper::Resource

  property :id,    Integer, :serial => true
  property :title, String
end

Post.auto_migrate!
first_post = Post.new
first_post.title = "First!"
first_post.save

get "/" do
  Post.get(1).title
end
Bob Aman
I'll take a look at DataMapper. Thanks for the code sample.
Chris Collins
when you use 'DataMapper.setup(:default, "sqlite3::memory")' , is that an im-memory db? How would you persist that to disk, or how would you open an existing sqlite db file?
LoveMeSomeCode
`DataMapper.setup(:default, "sqlite3:path/to/db/file.db")`
Bob Aman