Skip to content

Instantly share code, notes, and snippets.

@MTen
Created January 9, 2014 01:58
Show Gist options
  • Save MTen/8328140 to your computer and use it in GitHub Desktop.
Save MTen/8328140 to your computer and use it in GitHub Desktop.
This is how I understand rails CR .app without U or D.
A Rails CR .app with out the U or D
Create
Adding new records or objects to your database
.new(:stuff => “things")
The most basic way to create a new model object is with the new method. This record only lives in memory until .save is called on the object. Without calling .save on the object it will not be recorded to the database.
Possible applications: creating a new model object that lives in sessions until the user does a final submit action.
.create(:morestuff => “other things”)
This will create and save an object in one fell swoop. In this case its passing a hash of attributes to the create method. Normally we need to denote a hash with curly braces { :large_intestine => “poop" } but when a hash is the last argument of a Ruby method the braces are optional. You can also create a hash and then pass it through the .create method.
Read
Also known as finding an item in your database.
There a few ways (that I know of) to find objects in a database
.first
This method will return the first record of the table you’re calling the method. This will always return a single object/item unless the table is empty or has been dropped like a hot beat.*
.last
The last method works the same way but recalls the last record.*
*Keep in mind that this takes into account how you’re sorting the data in your tables.
.all
Something we’ve used a bunch of times. This will return all the tables records and let you cache them into an object which you can then play with and do stuff to.
.find(id)
This will return a record associated with the specified id. You can then call the keys of your object on this record. You can also pass an array of ids as the parameter and get back an array of hashes with all the records that match.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment