Skip to content

Instantly share code, notes, and snippets.

@TXDynamics
Last active December 16, 2015 12:59
Show Gist options
  • Save TXDynamics/5438976 to your computer and use it in GitHub Desktop.
Save TXDynamics/5438976 to your computer and use it in GitHub Desktop.
Active Record Transactions for manipulating the database
# You can define any model in the singular like User
# this should match the DB table users in the plural form
# then you can access that as a model as the following object
# When you want the first user in the DB table
user = User.first
# Then you can access the attributes by specifying the column
puts user.name
# You can then make a user in two parts
user = User.new(name: 'Blake', password: 'New')
# Then you would have to execute
user.save
# Or you can run it all at once using the create method
User.create(name: 'Blake', password: 'New')
# These are some examples of Active Record 'Transactions'
# Finding Records where 2 is the 'id' primary key of the record set
user = User.find(2)
# deleting a db record where the 'id' is '2'
user= User.find(2)
user.destroy
# Find a record based on a db column called 'email'
user = User.find_by_email('bwiedman@gmail.com')
# Now we want to update the email of a user with the 'id' of '2'
user = User.find(2)
user.email = 'new-email@gmail.com'
user.save
# If you want to update more than one attribute you should use the
# update_attributes followed by the hashes This also adds the save
# step similar to .create vs .new
user = User.find(2)
user.update_attributes(email: 'bwiedman@gmail.com', name: 'Blake')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment