我一直在研究与数据库交互并在数据库中存储信息。目前,我正在为我的编程课程开发一个项目,我正在尝试创建一个注册页面。此时,在我的signup.html
文件中,表单有两个输入:用户名和密码。然后,一旦提交,它将转到我的app.rb
文件中的post方法root。现在,在app.rb
文件中,在/sources
根目录(我的signup.html
文件中的表单的post方法根目录)中,我已将其输入凭据保存在我的数据库中。现在我想让数据库进行交叉检查以确保没有人拥有与刚刚输入的用户名相同的用户名。换句话说,如果已经使用了用户名,则无法注册。如果使用了用户名,我想要显示一条消息,说明用户需要输入新的所需用户名。如果未使用用户名,我希望它重定向到我创建的home.html
文件。我做过研究,发现这样做的方法是使用SELECT column_name FROM table_name
。但我不知道在哪里放这个代码。它是否位于/sources
文件中的app.rb
根目录下?
非常感谢任何帮助。这是我的代码:
在我的signup.html
文件中:
<p>Please fill out the information below to sign up.</p>
<form action = "/sources" method="post">
Username: <input type="text" name ="username" placeholder="Username"></br>
Password: <input type="password" name ="password" placeholder="Password"></br>
<input type="submit" value="Submit">
</form>
在我的app.rb
文件中:
require 'sinatra'
require 'sequel'
require 'rubygems'
require 'simple-rss'
require 'open-uri'
DB = Sequel.connect('sqlite://test.db')
get '/chart' do
DB.create_table(:db) do
primary_key :id
String :username
String :password
end
#I realize this is not a professional way of creating the database
# but I'm not looking for how to change this at the moment
end
post '/sources' do
@username = params[:username]
@password = params[:password]
@items = DB[:db]
@items.insert(:username => @username, :password => @password)
end
get '/signup' do
redirect 'signup.html'
end
答案 0 :(得分:0)
如果您这样做是专业的,那么您可以将应用分成几层。在您处于业务或逻辑层的路由中,然后您将数据请求移交给数据库层。数据库层可能由和ORM(如Sequel,Datamapper或ActiveRecord等)处理,在那里您将查询数据库,处理新用户的创建等,然后向逻辑层报告,然后逻辑层可以做出决定至于指导用户的路线和信息。
查看Sequel documentation on models并设置一个处理这些内容的User
模型,然后返回User
个实例或(可能)nil
,像那样。您需要在模型中使用self.exists?
等方法。
你真的应该将创建表语句移出路线,如果你不打算使用migrations(提示:你应该,它同样快)你可能想要也可以添加DB.table_exists?
方法。
用户名栏上的unique constraint也可能是一个好主意。