Granite
Github
Amber
Search…
README
Documentation
Callbacks
CRUD
Bulk Insertions
Migrations
Model Usage
Querying
Relationships
Errors
Powered By
GitBook
CRUD
Create
Combination of object creation and insertion into database.
1
Post.create(name: "Granite Rocks!", body: "Check this out.") # Set attributes and call save
2
Post.create!(name: "Granite Rocks!", body: "Check this out.") # Set attributes and call save!. Will throw an exception when the save failed
Copied!
Insert
Inserts an already created object into the database.
1
post = Post.new
2
post.name = "Granite Rocks!"
3
post.body = "Check this out."
4
post.save
5
6
post = Post.new
7
post.name = "Granite Rocks!"
8
post.body = "Check this out."
9
post.save! # raises when save failed
Copied!
Read
find
Finds the record with the given primary key.
1
post = Post.find 1
2
if post
3
puts post.name
4
end
5
6
post = Post.find! 1 # raises when no records found
Copied!
find_by
Finds the record(s) that match the given criteria
1
post = Post.find_by(slug: "example_slug")
2
if post
3
puts post.name
4
end
5
6
post = Post.find_by!(slug: "foo") # raises when no records found.
7
other_post = Post.find_by(slug: "foo", type: "bar") # Also works for multiple arguments.
Copied!
first
Returns the first record.
1
post = Post.first
2
if post
3
puts post.name
4
end
5
6
post = Post.first! # raises when no records exist
Copied!
where, order, limit, offset, group_by
See
querying
for more details of using the QueryBuilder.
all
Returns all records of a model.
1
posts = Post.all
2
if posts
3
posts.each do |post|
4
puts post.name
5
end
6
end
Copied!
See
querying
for more details on using
all
Update
Updates a given record already saved in the database.
1
post = Post.find 1
2
post.name = "Granite Really Rocks!"
3
post.save
4
5
post = Post.find 1
6
post.update(name: "Granite Really Rocks!") # Assigns attributes and calls save
7
8
post = Post.find 1
9
post.update!(name: "Granite Really Rocks!") # Assigns attributes and calls save!. Will throw an exception when the save failed
Copied!
Delete
Delete a specific record.
1
post = Post.find 1
2
post.destroy if post
3
puts "deleted" if post.destroyed?
4
5
post = Post.find 1
6
post.destroy! # raises when delete failed
Copied!
Clear all records of a model
1
Post.clear #truncate the table
Copied!
Previous
Callbacks
Next
Bulk Insertions
Last modified
2yr ago
Copy link
Contents
Create
Insert
Read
find
find_by
first
where, order, limit, offset, group_by
all
Update
Delete