开发者

Datamapper doesn't save data into database

开发者 https://www.devze.com 2022-12-20 22:54 出处:网络
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

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开发者_StackOverflow 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)


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

精彩评论

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

关注公众号