2010-02-20 100 views
2

我正在使用Sinatra和Datamapper在Ruby中編寫一個簡單的應用程序,並且遇到了麻煩 - 當我嘗試將數據保存到SQLite數據庫時,沒有任何更改。但是,當我嘗試安裝數據庫或從irb更改數據時,它可以很好地工作。Datamapper不會將數據保存到數據庫中

,這裏是我的DataMapper的設置,模型和數據庫安裝方法(這工作正常):

 
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 

下面是一段代碼,無法正常工作:

 
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 

這工作正常在irb中:

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

有誰知道有什麼問題?

P.S:我目前在Windows 7中工作,紅寶石版本是1.9.1p243(2009-07-16修訂24175)

+0

哦,我忘了寫在這裏的解決方案。爲了讓這件事情起作用,我不得不將to_i方法應用於params [:parent_id]。 – 2010-03-12 07:35:38

回答

1

嘗試測試頁#更新的返回值。如果某些數據無效,它將返回false並將頁面錯誤設置爲所有錯誤。 (假設你使用的DM-驗證)

BTW,編寫更新線路簡單的方法是:

@page.update(params.only(:title, :parent_id, :slug, :body)) 
+0

另外,我想,Sinatra並不象徵參數的關鍵。順便說一下,'only'是一個相當整潔的extlib散列擴展。 – BaroqueBobcat 2010-02-20 21:06:27

+0

我試過你的建議。更新方法現在返回true,但仍不保存數據。保存! Methos具有相同的行爲。 – 2010-02-21 03:55:59