CRUD with Active Record

Say you’re creating a blog. A blog has many posts, and a post belongs to a blog. I’ll use the “Post” class for these examples, however these can be substituted with any class name (capital and singular!).

Create

There’s essentially a couple of ways to create a new record.

One way of doing it:

p = Post.new(attributes…)
p.save

Another way of doing it:

p = Post.create(attributes…) # which will both create and save (essentially, it’s new + save in one)

One very important thing to notice here is that if you don’t use a destructive method (create!), if you are in your console you might think that the record is saved:

#<Post id: nil, name: “CRUD and Rails”, description: nil, …..>

However, when that id is nil, it means that something went wrong and did not save properly. This could be avoided by putting the ! on the method, which will then return an error:

=> ActiveRecord::RecordInvalid: Validation failed: description can’t be blank

Ah, and now we can see that it was a failed validation (that’s in the model).

Read

There’s many methods for reading a record. These include:

Post.find(2) -> where 2 is the record id

You can also get back an array with:

Post.find(3,5,7)

There’s also:

.first
.last
.all
.count
.order(:attribute) -> where the attribute is any attribute you want it ordered by, example :user_id
.limit(n) -> to limit the amount of records shown

and of course, there’s the “where” keyword

Post.where(attribute: value) -> where you can search for any specific value, example: Post.where(tag: “Rails”)

and the best thing, as usual, is method chaining it all together:

Post.where(attribute: value).order(:tag_name).limit(3)

You can do magic with Rails :D

Update

To update an attribute (or a param) of the record:

p = Post.find(4)
p.update_attributes(attribute: newvalue)

And as with the create example, you can use either a bang or not, depending on how you handle errors.

Destroy

You can delete either one selected record or all of them.

The keywords are esentially .destroy / .destroy_all

p = Post.find(3)
p.destroy
Post.destroy_all

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>