如何添加行到PostqreSQL使用activerecord-sinatra?

时间:2019-04-07 09:21:00

标签: ruby postgresql sinatra sinatra-activerecord

稍后我安装了PostgreSQL

1-已安装的宝石pg

2-已安装的宝石:

gem install activerecord 
gem install sinatra-activerecord 
gem install rake

3-我创建了连接数据库到文件app.rb

# 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:createrake db:migration

已创建数据库,将显示psql控制台中的数据库。现在如何在sinatra中向数据库添加行?

1 个答案:

答案 0 :(得分:2)

要创建新文章,请使用:

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文档:

  1. 持久性-https://www.rubydoc.info/gems/activerecord/ActiveRecord/Persistence

  2. 要查找:https://www.rubydoc.info/gems/activerecord/ActiveRecord/FinderMethods

  3. 对于复杂的查询:https://www.rubydoc.info/gems/activerecord/ActiveRecord/QueryMethods