2

I am currently building a small app with Sinatra and have run up against an issue saving form data to the mysql database. Firstly I can confirm that the connection to the database is working as I am logging into the app with twitter auth and it is saving dat into its table.

The form is simple

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>

The model looks like so

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!

and the sinatra route is like this:

 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

Now for some reason every time I enter the form is comes back with the I didnt save flash. Im sure this is an obvious thing but I juts cant see where Im going wrong anywhere.

Sam Mason
  • 1,037
  • 1
  • 8
  • 29
  • Why are you not logging the errors that dataMapper returns when save fails? Specifically, log @weight.errors - it should enumerate any validations which failed. – mcfinnigan Mar 25 '13 at 10:40
  • Im not sure how to do that do I nee to just need to output that in the view? – Sam Mason Mar 25 '13 at 10:45
  • Thanks, your question made me realise I was missing method="post" on my form tag :) – ConorLuddy Mar 04 '14 at 23:30

2 Answers2

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

Ideally, though, you should set up a logger and log what you're up to. This makes things far easier to debug.

mcfinnigan
  • 11,442
  • 35
  • 28
0

I solved this using the help of logging my errors to the console thanks to mcfinnigans comment.

The database was expecting a number but as the form was using a text box it attempted to save as a string. so i added .to_f to my amount param to convert it.

Sam Mason
  • 1,037
  • 1
  • 8
  • 29