开发者

Form Data is not getting posted to DataMapper DB

I have a simple Sinatra app I'm playing with, trying to learn the ropes. I have simple form, but the data is not posting. I am using DataMapper to connect to the database, but the data is not getting posted (the DB shows entries, bu开发者_StackOverflow中文版t they're all blank).

Here is my form:

<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>

And my Sinatra file with all the handlers (incomplete, obviously):

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


Setting the enctype on your html form tag prevents Sinatra from reading the POST. If you strip that off, the parameters will be set and therefore passed to the Entry.new call. If you wish to explicitly set it (to the same value as the default,) then it is:

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


Try

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

If you don't use form builders or resources, you don't get symbols in params.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜