Create, Update, Save and Destroy
To illustrate the various methods used in manipulating records, we’ll create, save and destroy a record.
1 class Zoo 2 include DataMapper::Resource 3 property :id, Integer, :serial => true 4 property :name, String 5 property :description, Text 6 property :inception, DateTime 7 property :open, Boolean, :default => false 8 end
Creating
Let’s create a new instance of the model, update its properties and save it to the data store. Save will return true if the save succeeds, or false when something went wrong.
1 zoo = Zoo.new 2 zoo.attributes = {:name => 'The Glue Factory', :inception => Time.now} 3 zoo.save
Pretty straight forward. In this example we’ve updated the attributes using the #attributes= method, but there are multiple ways of setting the values of a model’s properties.
1 zoo = Zoo.new(:name => 'Awesome Town Zoo') # Pass in a hash to the new method 2 zoo.name = 'Dodgy Town Zoo' # Set individual property 3 zoo.attributes = {:name => 'No Fun Zoo', :open => false} # Set multiple properties at once
You can also update a model’s properties and save it with one method call. #update_attributes will return true if the record saves, false if the save fails, exactly like the #save method.
1 zoo.update_attributes(:name => 'Funky Town Municipal Zoo')
Destroy
To destroy a record, you simply call it’s #destroy! method. It will return true or false depending if the record is successfully deleted. Here is an example of finding an existing record then destroying it.
1 zoo = Zoo[5] 2 zoo.destroy! #=> true