2

我目前正在使用 Sinatra 构建一个小型应用程序,并且遇到了将表单数据保存到 mysql 数据库的问题。首先,当我使用 twitter auth 登录应用程序并将 dat 保存到其表中时,我可以确认与数据库的连接正在工作。

表格很简单

route: '/'
<form action="/create" method="post">
    <p>
        <label for="">Weight</label>
        <input type="text" name="weight[amount]">
    </p>
    <p>
        <input type="submit" id="">
    </p>
</form>

模型看起来像这样

class Weight
   include DataMapper::Resource
   property :id,         Serial, key: true
   property :amount,     Float 
   property :is_goal,    Boolean, :default  => false
   property :created_at, DateTime, :required => true
   belongs_to :user
end

DataMapper.finalize
DataMapper.auto_upgrade!

西纳特拉路线是这样的:

 post '/create' do
    @weight = Weight.create(params[:weight])
 if @weight.save 
    flash[:success] = "Its all saved now"
    redirect '/'
 else
    flash[:failure] = "I Didnt save!"
    redirect '/'
 end
 end

现在由于某种原因,每次我输入表格时都会I didnt save闪回。我确定这是一件显而易见的事情,但我看不出我哪里出错了。

4

2 回答 2

2
  post '/create' do
  @weight = Weight.create(params[:weight])

  if @weight.save 
    flash[:success] = "Its all saved now"
    redirect '/'
   else
    flash[:failure] = "I Didnt save!"
    STDERR.puts @weight.errors.inspect # <-- will dump the errors structure to STDERR
    redirect '/'
   end
 end

不过,理想情况下,您应该设置一个记录器并记录您在做什么。这使得事情更容易调试。

于 2013-03-25T11:03:22.910 回答
0

由于 mcfinnigans 的评论,我通过将错误记录到控制台的帮助解决了这个问题。

数据库期待一个数字,但由于表单使用文本框,它试图保存为字符串。所以我添加.to_f到我的金额参数来转换它。

于 2013-03-25T11:38:40.367 回答