mysql数据库如何解决这个问题?

时间:2017-02-14 03:38:47

标签: mysql ruby activerecord sinatra

您好我正在尝试使用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

1 个答案:

答案 0 :(得分:0)

通常,您将代码分成多个文件(我们使用名为config,帮助程序,库,视图,路由,模型,迁移的文件夹),并在应用程序的顶部需要它们。但是,如果你想把它放在同一个文件中,只需使用它和一个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 app
  • 使用ERB查看

2)宝石的Bundler文档 - http://bundler.io/

3)ActiveRecord文档 - http://guides.rubyonrails.org/active_record_basics.html

  • 连接数据库通过迁移创建数据库 - 这是查询数据库的一次性交易

祝你好运!