markdown 使用Active Record设置Sinatra

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 使用Active Record设置Sinatra相关的知识,希望对你有一定的参考价值。

# Setting up Sinatra Project

create an empty project and add a Gemfile

```bash
cd ~/Desktop
mkdir project-name
cd project-name
touch Gemfile
```

```ruby
# Gemfile
source 'https://rubygems.org'

gem 'activerecord'
gem 'sinatra-activerecord'
gem 'sqlite3'
gem 'rake'
```

Install the dependencies

```bash
bundle install
```

Create an app.rb file

```ruby
# app.rb
require 'sinatra'
require 'sinatra/activerecord'

set :database, "sqlite3:project-name.sqlite3"
```

Create a Rakefile

```ruby
# Rakefile
require 'sinatra/activerecord/rake'
require './app'
```

Create a migration for creating a users table

```bash
rake db:create_migration NAME=create_users_table
```

Add code to the migration for creating columns

```ruby
class CreateUsersTable < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :fname
      t.string :lname
      t.string :email
      t.datetime :created_at
      t.datetime :updated_at
    end
  end
end
```

Run the migration

```bash
rake db:migrate
```

Create a User model

```ruby
# models.rb
class User < ActiveRecord::Base
end
```

Load the User model into your app

```ruby
# at the bottom of app.rb
require './models'
```

Create a seeds file

```ruby
touch db/seeds.rb
```

Write some seeds

```ruby
# db/seeds.rb
users = [
  {fname: 'Jon', lname: 'Doe', email: 'e@example.com'},
  {fname: 'Jane', lname: 'Doe', email: 'e@example.com'}
]

users.each do |u|
  User.create(u)
end
```

Run the seeds

```ruby
rake db:seed
```

Create an index.erb file in a views directory (views/index.erb)

```erb
<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
</head>
<body>
    <ul>
        <% @users.each do |user| %>
            <li><%= user.email %></li>
        <% end %>
    </ul>
</body>
</html>
```

Create a route for the home page

```ruby
# app.rb
get '/' do
  @users = User.all
  erb :index
end
```

#### Adding more tables (models)

1. Create migration with rake
1. Populate the migration with code for adding columns
1. Run the migration with rake db:migrate
1. Create the model (add class to models file)
1. Add some rows to the table with IRB
1. Create a route and a view for displaying records

以上是关于markdown 使用Active Record设置Sinatra的主要内容,如果未能解决你的问题,请参考以下文章

脱离rails 使用Active Record

使用 CodeIgniter Active Record 语句

PHP Yii:在Active Record中使用MySQL的IN条件

Codeigniter Active Record使用多个主键选择多行

Active Record基础

Codeigniter Active Record 中的 Concat