【问题标题】:mysql Databases how can I fix this?mysql数据库我该如何解决这个问题?
【发布时间】:2017-07-02 05:31:09
【问题描述】:

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

【问题讨论】:

  • 这里有什么问题?这是相当混乱的代码。
  • 是的,抱歉,我查看了太多资源,并认为我组合了错误的语法。我无法启动数据库,因为我遇到了错误。主要错误是我缺少一个参数@tadman
  • 错误在解释您的问题时有不可估量的帮助,因此您需要传达这些错误是什么以及它们所指的行。
  • ok ernel_require.rb:55:in `require' 是它在终端中所说的,但我很难破译它。
  • 一切直到 ActiveRecord::Base。是正确的

标签: mysql ruby activerecord sinatra


【解决方案1】:

通常,您将代码分解为多个文件(我们使用名为 config、helpers、libraries、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

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

祝你好运!

【讨论】:

  • 非常感谢。这是一个很好的建议。当我试图做到这一点时,我在课堂上抢先学习它。现在我对你的指导有了更好的把握,并且确切地知道该怎么做。再次感谢!
猜你喜欢
  • 2020-03-25
  • 2020-02-14
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2021-07-31
相关资源
最近更新 更多