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

匆匆过客 提交于 2019-11-30 06:15:50

问题


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?


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/777724/whats-the-best-way-to-talk-to-a-database-while-using-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!