使用DataMapper保存数据

时间:2011-12-01 15:32:05

标签: ruby orm datamapper

我正在尝试保存到sqlite 3数据库。我似乎无法保存,但不会抛出任何错误。我究竟做错了什么?我从我之前存在的一段有效的代码中取出了保存例程。关于我接下来应该尝试什么的任何想法?

require 'data_mapper'
require 'dm-migrations'

DataMapper.setup :default, "sqlite://#{Dir.pwd}/development.sqlite3"

class Post
  include DataMapper::Resource
  property :title,      String, :key => true # An auto-increment integer key
  property :slug_url,   String   
  property :desc,       String
  property :content,    String
  property :project,    String
  property :target_url, String
  property :trackback,  Boolean
  property :updated_at, String
  property :created_at, DateTime  # A DateTime, for any date you might like.
end

DataMapper.finalize
DataMapper.auto_upgrade!

post = Post.new
post.attributes = {:title => "Title",
                :slug_url => "Some-slug-url",
                :content => "content",
                :target_url => "http://example.com",
                :trackback => false
}
post.save

2 个答案:

答案 0 :(得分:0)

我不确定为什么这种方式有所不同,但我通过这样做得到了它:

require 'data_mapper'
require 'dm-migrations'

DataMapper.setup :default, "sqlite://#{Dir.pwd}/development.sqlite3"

class Post
  include DataMapper::Resource
  property :title,      String, :key => true # An auto-increment integer key
  property :slug_url,   String    # A varchar type string, for short strings
  property :desc,       String
  property :content,    String
  property :project,    String
  property :target_url, String
  property :trackback,  Boolean
  property :updated_at, DateTime
  property :created_at, DateTime  # A DateTime, for any date you might like.
end

DataMapper.finalize
DataMapper.auto_upgrade!

post = Post.new(:title => "Title",
                    :slug_url => "Some-slug-url",
                    :content => "content",
                    :target_url => "http://example.com",
                    :trackback => false)
post.save

答案 1 :(得分:0)

可以使用DataMapper::Model.raise_on_save_failure = true修复“不会抛出任何错误”部分,DataMapper默认情况下不会保释。 #save!是不安全的版本(不知道为什么ActiveRecord对bang使用完全不同的语义)。 For further information, read here.

引发的第一个错误是column title is not unique (DataObjects::IntegrityError)。猜猜发生了什么; - )