Combination of object creation and insertion into database.
Post.create(name: "Granite Rocks!", body: "Check this out.")# Set attributes and call savePost.create!(name: "Granite Rocks!", body: "Check this out.") # Set attributes and call save!. Will throw an exception when the save failed
Insert
Inserts an already created object into the database.
post =Post.newpost.name ="Granite Rocks!"post.body ="Check this out."post.savepost =Post.newpost.name ="Granite Rocks!"post.body ="Check this out."post.save! # raises when save failed
Read
find
Finds the record with the given primary key.
post =Post.find 1if postputs post.nameendpost =Post.find! 1# raises when no records found
find_by
Finds the record(s) that match the given criteria
post =Post.find_by(slug: "example_slug")if postputs post.nameendpost =Post.find_by!(slug: "foo")# raises when no records found.other_post =Post.find_by(slug: "foo", type: "bar")# Also works for multiple arguments.
first
Returns the first record.
post =Post.firstif postputs post.nameendpost =Post.first! # raises when no records exist
where, order, limit, offset, group_by
See querying for more details of using the QueryBuilder.
all
Returns all records of a model.
posts =Post.allif posts posts.each do |post|puts post.nameendend
Updates a given record already saved in the database.
post =Post.find 1post.name ="Granite Really Rocks!"post.savepost =Post.find 1post.update(name: "Granite Really Rocks!")# Assigns attributes and calls savepost =Post.find 1post.update!(name: "Granite Really Rocks!") # Assigns attributes and calls save!. Will throw an exception when the save failed
Delete
Delete a specific record.
post =Post.find 1post.destroy if postputs"deleted"if post.destroyed?post =Post.find 1post.destroy! # raises when delete failed