Chris Collins
Chris Collins

Reputation: 3440

What's the best way to talk to a database while using Sinatra?

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?

Upvotes: 34

Views: 24281

Answers (3)

Mike Woodhouse
Mike Woodhouse

Reputation: 52326

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 'active_record'

class Article < ActiveRecord::Base
end

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

Upvotes: 31

user
user

Reputation: 25738

It is up to you how to communicate with a database, you may choose either one of the ORMs or some NoSQL adapter. There are many options available, some of them were made specially for Sinatra:

For example, there is Sinatra ActiveRecord Extension
Originally created by Blake Mizerany, creator of Sinatra
It extends Sinatra with ActiveRecord helper methods and Rake tasks

Another option is Sinatra Sequel Extension.
This small extension adds database configuration, migrations, and Sequel adapters right into Sinatra.

Or sinatra-redis, or sinatra-mongo, and so on. Just search for what you want.

But you may as well freely use any independent library, check out the Sinatra Recipes on databases, where is listed a couple of examples of how to use popular database mappers with Sinatra. Although it is mentioned there that the suggested practice for this is using DataMapper, I suspect that this is a mere preference, because nothing in Sinatra itself suggests this.

Upvotes: 0

Bob Aman
Bob Aman

Reputation: 33239

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

Upvotes: 63

Related Questions