Skip to content

Instantly share code, notes, and snippets.

@keeperofthenecklace
Created August 27, 2012 15:23
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 keeperofthenecklace/3489459 to your computer and use it in GitHub Desktop.
Save keeperofthenecklace/3489459 to your computer and use it in GitHub Desktop.
ActiveRecord
ActiveRecord
-----------
SERIALIZED ATTRIBUTE
$ rails c --sandbox or rails c development
#create class method
$ user = User.create( name" "albert", email: "kotn_ep1@hotmail.com" )
#new class method
1.9.3p194 :006 > user = User.new do |u|
1.9.3p194 :007 > u.name = "Isaace McKeever"
1.9.3p194 :008?> u.email = "Isaac@hotmail.com"
1.9.3p194 :009?> u.password = "kwame1"
1.9.3p194 :010?> u.password_confirmation = "kwame1"
1.9.3p194 :011?> end
1.9.3p194 :011?> user.save
$ user.new_record? #=> true
$ user.persisted? #=> false
READ ACTIVERECORD OBJECTS
--------------------------
Person.find(1) # returns the object for ID = 1
Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
Person.find([1]) # returns an array for the object with ID = 1
Person.where("administrator = 1").order("created_on DESC").find(1)
User.where("name = ? AND email = ?", 'Albert Mckeever', 'kotn_ep1@hotmail.com')
param = "mckeever"
User.where("name LIKE ?", "#{params}%")
1.9.3p194 :055 > user.attributes
=> {"id"=>1, "name"=>"Albert Mckeever", "email"=>"kotn_ep1@hotmail.com", "created_at"=>Mon, 27 Aug 2012 15:31:04 UTC +00:00, "updated_at"=>Mon, 27 Aug 2012 "}
:from - Sets the path or custom method that resources will be fetched from.
:params - Sets query and prefix (nested URL) parameters.
Person.find(:all, :params => { :title => "CEO" })
DYNAMIC SCOPES
-------------
user = User.scoped_by_name("albert McKeever").order(:created_at)
$ scope_by_name is now a method on User. Check it out by typing
$ User.methods.grep(/scope/)
1.9.3p194 :131 > User.methods.grep(/scope/)
=> [:scoped_by_name, :scoped_by_email,
CUSTOM SQL QUERIES
-------------------
$ = User.find_by_sql("SELECT * FROM users")
$ user = User.find_by_sql(" SELECT `users`.* FROM `users` WHERE `users`.`name` = 'albert McKeever' ORDER BY created_at")
$ user = User.find_by_sql(" SELECT * FROM `users` WHERE name LIKE '%mckeever'")
$ user = User.count_by_sql("select count(*) from users")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment