I have a database schema like that
DataMapper.setup :default, "sqlite://#{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:
Please note that to use validation errors you need to require ‘dm-validations’ gem.