Sinatra, MySQL and ActiveRecord

人走茶凉 提交于 2019-12-03 00:49:17

This is a dead simple Sinatra-MySQL-ActiveRecord application. It has 2 files:

Gemfile and app.rb

Gemfile:

source :rubygems
gem 'sinatra', '1.3.1'
gem 'activerecord', '3.2.13'

app.rb

require 'rubygems'
require 'sinatra'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter  => "mysql2",
  :host     => "host",
  :username => "user",
  :password => "password",
  :database => "db"
)

class User < ActiveRecord::Base
end

ActiveRecord::Migration.create_table :users do |t|
  t.string :name
end

class App < Sinatra::Application
end

get '/' do
  p User.all
end
  1. Create these 2 files
  2. do bundle install (gem install bundler if you havent)
  3. ruby app.rb

You should read how to insert data using ActiveRecord. In this case, you can manually enter some data to the table from MySQL and see the output.

You can still use sinatra-activerecord gem with MySQL and avial other features too.

Following is the way to use it:

require "sinatra/activerecord"

set :database, "mysql2://#{db_username}:#{db_password}@#{db_host}:#{db_port}/#{db_database}"

# Model
class User < ActiveRecord::Base
end 

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