Rails Console / Active Record (Object Relational Mapping) – Basics (CRUD) 1

Console

$rails console

get Model information (Article):

/* inherited from ActiveRecord::Base */

>>Article.column_names

full info:

>>Article

>>Article.methods.size (will return # of available methods!)

ActiveRecord Basics: CRUD

create

>>article = Article.new (create new Model object with constructor)

>>article.new_record? (returns =>true)

>>article.title = ‘blahblah’ (setter)

alternate: >>article = Article.new(:title=>’blahblah’)

>>article (outputs new article and set variables, in this case just title)

>>article.save

>>Article.count (returns 1)

>>article.new_record? (false)

create instead of save, all in one step:

>>Article.create(:title=>’blahblah’)

or

>>attributes = {:title=>’blahblah’}

>>Article.create(attributes)

read

find(:id) / find(:all)  / find(:first) / find(:last)

>>Article.find(3)

>>article = Article.find(3)

>>article.id (returns 3)

>>Article.first

>>Article.last

>>article = Article.all

>>articles.class (returns Array)

>>articles.size (returns integer)

>>articles[0] / >>articles[0].title

>>articles.first.title

loop

>>articles.each{|article| puts article.title}

order, where

>>articles = Article.order(“published_at”) (order return by desired field)

>>Article.where(:title => ‘blahblah’).first

>>Article.where(:title => ‘blahblah’).all

dynamic

find_by_*(cond) – example: find_by_title(‘blahblah’)

find_all_by_*(cond)

find_by_*_and_*(cond1,cond2)

find_all_by_*_and_*(cond1,cond2)

update

>>article = Article.first

>>article.title = ‘notblah’

>>article.save

in one call

>>article = Article.first

>>article.update_attributes(:title=>’notblah’)

delete

  • destroy works on the instance, instantiates the object, finds a single row, then deletes

>>article = Article.last

>>article.destroy

or one line

>>Article.last.destroy

>>Article.destroy(3) // by id

>>Article.destroy([2,3])

  • delete operates on the class, on the table rather than a given row from that table

>>Article.delete(4)

>>Article.delete([5,6])

>>Article.delete_all(“published_at < ‘2001-01-01′”)

check validation

>>article = Article.new

>>article.errors.any? // returns bool

>>article.errors.full_messages // returns specified message

>>article.errors.on(:title)

>>article.errors.size

>>article.valid?

 

Leave a Reply

You must be logged in to post a comment.