Sinatra, MySQL and ActiveRecord

后端 未结 2 1120
天涯浪人
天涯浪人 2021-02-03 16:18

how do I set up a simple sinatra app to use MySQL and ActiveRecord? I found some solutions, but none of them worked (maybe they are outdated):

http://ericfarkas.com/post

2条回答
  •  耶瑟儿~
    2021-02-03 16:37

    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.

提交回复
热议问题