views:

317

answers:

1

Hi! I'm writing a simple application with Sinatra and Datamapper in Ruby and I have a trouble — when I try to save data into my SQLite database nothing is changing. But when I try to install database or change data from irb it works perfectly.

Here is my Datamapper's setup, model and database installing method (this works fine):

DataMapper.setup(:default, "sqlite3://#{File.dirname(__FILE__)}/db.sqlite")

class Page
  include DataMapper::Resource

  property :id,         Serial
  property :parent_id,  Integer
  property :title,      String, :length => 0..255
  property :slug,       String, :length => 0..255
  property :body,       Text
  property :created_at, DateTime

  def children
    Page.all(:parent_id => self.id)
  end

  def install
    DataMapper.auto_migrate!

    Page.new(:parent_id => 0,
             :title => "Main",
             :slug => "/",
             :body => "This is the Main Page. Replace it's text with yours",
             :created_at => Time.now).save!

  end
end

And here's piece of code that doesn't work correctly:

post %r{/admin/edit/([\d]+)/?} do
  protected!
  #works fine and gets a row from database
  @page = Page.get(params[:captures].first)
  #update doesn't work, the save! method doesn't work too
  @page.update  :title => params[:title],
                :parent_id => params[:parent_id],
                :slug => params[:slug],
                :body => params[:body]
  redirect request.path_info
end

This works fine in the irb:

p = Page.get(1)
p.update :title => "testing update"

Does anybody knows what's the problem?

P.S.: I'm currently working in Windows 7, ruby version is 1.9.1p243 (2009-07-16 revision 24175)

+2  A: 

Try testing the return value of Page#update. If some of the data was invalid, it will return false and set the Page#errors variable with all the errors. (assuming you are using dm-validations)

BTW, a simpler way to write that update line is:

@page.update(params.only(:title, :parent_id, :slug, :body))
dkubb
Also, Sinatra doesn't symbolize the keys of the params, I think. `only` is a pretty neat extlib hash extension, by the way.
BaroqueBobcat
I've tried your advice. The update method returns true now but still doesn't save data. The save! methos has the same behaviour.
OutPunk