开发者

ruby datamapper can't save to database

I have a database schema like that

DataMapper.setup :default, "s开发者_如何学Goqlite://#{Dir.pwd}/image.db"
class Image
    include DataMapper::Resource

    property :id       , Serial
    property :url , String,unique: true
    property :desc    , String,unique: true,default: "empty"
end
DataMapper.finalize.auto_upgrade!

Then i have a loop like this

links.each do |link|
  puts link
  if Image.all(:url=>link).empty? == true
    img=Image.create(:url => link)
    puts "Cannot save to database "if img.saved? == false
  end
end

I want to add a link when it is not already in a database. I run the script and always get cannot save to dabase. What am I doing wrong? Thanks for any help. Edit: I add to my code

DataMapper::Logger.new($stdout, :debug)

and there was no insert queries only selects.


You declared :desc property to be unique and set default value to "empty" and in your code example you're creating Image without specifying :desc which results in uniqueness validation failure, that's why your images aren't saved. You can either remove unique option from :desc property declaration or make sure to provide unique value for :desc when creating images.

Also, to make your code more verbose so you could see any validation errors try this:

links.each do |link|
  image = Image.new(:url => link)

  if image.save
    puts "Image saved"
  else
    puts "Failed to save image: #{image.errors.inspect}"
  end
end

Please note that to use validation errors you need to require 'dm-validations' gem.


What do you mean you get "cannot save to database"?

You can try something like this and see if it works a bit better:

links.each do |link|
  if Image.first(:url => link)
    p "image exists"
  else
    if Image.create(:url => link) 
      p "Image succesfully saved"
    else
      p "could not save image"
    end
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜