Skip to content

Instantly share code, notes, and snippets.

@florida
Created October 6, 2012 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florida/3845787 to your computer and use it in GitHub Desktop.
Save florida/3845787 to your computer and use it in GitHub Desktop.
Active Record
# Reading with active record
# inspecting an object
# this will output the value
puts Object.first.inspect
# counts the number of objects in the database
puts Object.count
puts Object.size
# Getting the first row in the database
puts Object.first.inspect
# Getting the last row in the database
puts Object.last.inspect
# getting all the customers and storing it into a variable
#create the object
#It will create a new object from the model Object
#That links to a Objects table in the database
new_entry = Object.new
#Add attributes to the object
new_entry.name = "Object Name"
#save the objects value to the database
new_entry.save
####Another way of creating entries
#create the object and pass the values as a hash.
second_entry = Object.new(:name => "Second Object", :description => "I'm an object in object space")
#save the object
second_object.save
####Another way of creating + saving the entries
#create the object
third_entry = Object.create(:name => "Third Object", :description => "I am also an object in database space"
# This is the object model, there exist in the database a table called Objects
class Object < ActiveRecord::Base
validates_presence_of :name, :description
belongs_to :type
end
# The type model, in the database there's a table that has the name of Types
class Type < ActiveRecord::Base
validates_presence_of :type, :description
has_many :objects
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment