嗨,我正在尝试使用 ruby、sinatra、ActiveRecord 和 mysql 建立一个数据库来存储电子邮件。关于我做错了什么有什么建议吗?我试图将其输出到一个只有我可以看到的单独页面,然后使用 hostgator 上的 url 将其发布。
require 'sinatra'
require 'activerecord'
# require 'sinatra-activerecord'
get '/' do
erb :index
end
def save_email (email)
file.print(email)
end
get '/email' do
params[:email]
# # redirect '/'
end
post '/email' do
params[:email]
@email = params[:email]
erb :email, :locals => {:email => params[:email]}
end
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'mysql', # or 'postgresql'
host: 'localhost',
database: 'Stored_Emails',
)
class Stored_Emails < Sinatra::Application
end
class Stored_Emails < ActiveRecord::Base
end
ActiveRecord::Migration.create_table :email do |t|
t.string :emails
end
create_table :emails, force: true do |t|
t.string :email
t.belongs_to :email, index: true
end
get '/email' do
params[:email].all
end
最佳答案
通常,您将代码分解为多个文件(我们使用名为 config、helpers、library、views、routes、models、migrations 的文件夹),并要求将它们放在应用程序的顶部。但是,如果您想将其放在同一个文件中并仅使用该文件以及 Gemfile 和 Gemfile.lock 也可以。它可能是这样的:
# Require your gems
require 'sinatra'
require 'activerecord'
# Libraries
# Models
class Stored_Emails < ActiveRecord::Base
end
# Configuration
# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'mysql', # or 'postgresql'
host: 'localhost',
database: 'Stored_Emails'
)
ActiveRecord::Migration.create_table :email do |t|
t.string :emails
end
# Migrations
create_table :emails, force: true do |t|
t.string :email
end
# Helpers
def save_email (email)
file.print(email)
end
# Routes
get '/' do
# Load whatever you want to show in your index page into class variables
erb :index
end
get '/email' do
Stored_Emails.all.to_json
end
post '/email' do
@email = Stored_Emails.find_by(params[:email])
erb :email
end
现在您必须做大量工作才能使其运行。我建议您阅读以下内容:
1) Sinatra 文档 - http://www.sinatrarb.com/intro.html
- 路线
- 运行您的 sinatra 应用
- ERB 的看法
2) gems 的 bundler 文档 - http://bundler.io/
3) ActiveRecord 文档 - http://guides.rubyonrails.org/active_record_basics.html
- 连接到数据库通过迁移创建数据库 - 这是一次性交易查询数据库
祝你好运!
关于mysql 数据库我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42217463/