表单数据未发布到DataMapper DB

时间:2011-07-06 05:32:14

标签: ruby sinatra datamapper

我有一个简单的Sinatra应用程序,我正在玩,试图学习绳索。我有简单的表格,但数据不发布。我使用DataMapper连接到数据库,但数据没有发布(数据库显示条目,但它们都是空白的。)

这是我的表格:

<h1><%= @title %></h1>

<form action="/create" method="post" id="entry" enctype="text/plain">
<p>
<label>First Name: </label><br />
<input type="text" name="first_name" id="first_name" />
</p>
<p>
<label>Last Name: </label><br />
<input type="text" name="last_name" id="last_name" />
</p>
<p>
<label>Apple Email Address: </label><br />
<input type="text" name="email" id="email" />
</p>
<p>
<input type="submit">
</p>

我的Sinatra文件包含所有处理程序(显然不完整):

require 'sinatra'
require 'rubygems'
require 'datamapper'
require 'dm-core'

DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/entries.db")

class Entry
include DataMapper::Resource

property :id,           Serial
property :first_name,   String
property :last_name,    String
property :email,        String
property :created_at,   DateTime    

end

# create, upgrade, or migrate tables automatically
DataMapper.auto_upgrade!

# Set UTF-8 for outgoing
before do
headers "Content-Type" => "text/html; charset=utf-8"
end


get '/' do
@title = "Enter to win a rad Timbuk2 bag!"
erb :welcome
end

get '/entry' do
end

get '/list' do
@title = "List of Entries"
@entries = Entry.all(:order => [:created_at.desc])
erb :list
end

post '/create' do
@entry = Entry.new(:first_name => params[:first_name], :last_name =>     params[:last_name], :email => params[:email])

if @entry.save
    redirect("/thanks")
else
    redirect('/')
end
end

get '/thanks' do
erb :thanks
end

2 个答案:

答案 0 :(得分:1)

在html表单标签上设置enctype可防止Sinatra读取POST。如果将其剥离,则将设置参数,并将其传递给Entry.new调用。如果您希望显式设置它(与默认值相同的值),那么它是:

[...]
<form action="/create" method="post" id="entry" enctype="application/x-www-form-urlencoded">
<p>
  <label>First Name: </label><br />
[...]

答案 1 :(得分:0)

尝试

@entry = Entry.new(:first_name => params['first_name'], :last_name => params['last_name'], :email => params['email'])

如果您不使用表单构建器或资源,则不会在params中获取符号。