我后来安装了PostgreSQL
1 - 已安装的ruby pg
2 - 已安装的ruby:
gem install activerecord
gem install sinatra-activerecord
gem install rake
3 - 我创建了连接数据库到app.rb的文件
configure :development do set :database, {adapter: "postgresql", encoding: "unicode", database: "your_database_name", pool: 2, username: "your_username", password: "your_password"}
end
configure :production do
set :database, {adapter: "postgresql", encoding: "unicode", database: "your_database_name", pool: 2, username: "your_username", password: "your_password"}
end
4 - 创建app.rb文件的模型
class Article < ActiveRecord::Base
end
5 - 创建到Rakefile的迁移
require 'sinatra/activerecord'
require 'sinatra/activerecord/rake'
require './app'
6 - rake db:create_migration NAME=create_articles
7 - 在由文件迁移创建的新文件中
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :title
t.string :content
t.boolean :published, :default => false
t.datetime :published_on, :required => false
t.integer :likes, :default => 0
t.timestamps null: false
end
end
end
8 - 我完成了命令db:create和rake db:migration
创建数据库,显示psql控制台中的数据库。现在如何在sinatra中添加数据库线?
要创建新文章,请使用:
Article.create(title: your_title, content: your_content, published: true, published_on: Time.now)
按ID查找文章:
Article.find(id)
对于更新文章:
article = Article.find(id)
article.update(title: your_title, content: your_content, published: true, published_on: Time.now)
对于删除文章记录:
article = Article.find(id)
article.destroy
AR文件:
持久性 - https://www.rubydoc.info/gems/activerecord/ActiveRecord/Persistence
寻找:https://www.rubydoc.info/gems/activerecord/ActiveRecord/FinderMethods
对于复杂查询:https://www.rubydoc.info/gems/activerecord/ActiveRecord/QueryMethods
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。