西纳特拉,MySQL和ActiveRecord的 [英] Sinatra, MySQL and ActiveRecord

查看:118
本文介绍了西纳特拉,MySQL和ActiveRecord的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何建立一个简单的辛纳屈的应用程序使用MySQL和ActiveRecord的?我找到了一些解决方案,但它们都没有工作(也许他们是过时的):

http://ericfarkas.com/posts/sinatra-activerecord-and-mysql /

http://labs.thredup.com/setting-向上西纳特拉,与MySQL的 - 和 - activerecor

那么,什么是最好的练习方法,使用西纳特拉与MySQL和ActiveRecord的?该 https://github.com/janko-m/sinatra-activerecord 宝石只对于sqlite3的,据我所看到的。

我不知道如果我需要的模型或只是简单的SQL查询。但得到它的工作都在一起将帮助我很多东西。

解决方案

这是一个死的简单西纳特拉MySQL的-ActiveRecord的应用程序。它有2个文件:

的Gemfile app.rb

的Gemfile:

 来源:RubyGems的
创业板西纳特拉,1.3.1
创业板的ActiveRecord,3.2.13
 

app.rb

 需要'rubygems的'
要求辛纳特拉
需要'active_record

的ActiveRecord :: Base.establish_connection(
  :适配器=> mysql2
  :主机=> 主办,
  :用户名=> 用户,
  :密码=> 密码,
  :数据库=> DB
)

类用户的LT;的ActiveRecord :: Base的
结束

ActiveRecord的:: Migration.create_table:用户做| T |
  t.string:名称
结束

类应用<西纳特拉::应用
结束

得到'/'做
  p User.all
结束
 

  1. 创建这两个文件
  2. 捆绑安装创业板安装打捆如果您还没有)
  3. 红宝石app.rb

您应该阅读如何使用ActiveRecord的插入的数据。在这种情况下,您可以手动输入一些数据从MySQL表,并查看输出。

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/posts/sinatra-activerecord-and-mysql/

http://labs.thredup.com/setting-up-sinatra-with-mysql-and-activerecor

So what is the best practise method, to use Sinatra along with MySQL and ActiveRecord? The https://github.com/janko-m/sinatra-activerecord gem is only for sqlite3, as far as I can see.

I'm not sure if I need models or just plain SQL queries. But getting it to work all together would help me a lot.

解决方案

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.

这篇关于西纳特拉,MySQL和ActiveRecord的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆