RoR Active Record notes 3

Finding

Article.where(:title=>’Advanced Active Record’)

SQL Fragment

Article.where(“title = ‘Advanced Active Record'”)

Article.where(“created_at > ’23-03-2010′ OR body NOT LIKE ‘%model%'”)

Article.where(“created_at > ’23-03-2010′ AND body NOT LIKE ‘%model%'”)

Array Condition Syntax

Article.where(“published_at < ?”, Time.now)

Inspect the rendered SQL

Article.where(“published_at < ?”, Time.now).to_sql

Article.where(“created_at = ? OR body LIKE ?”, Article.last.created_at, ‘model’)

Print directly to the log file

logger.debug “This…”

logger.warn “all environments…”

Association Proxies

User.first.articles.all (example)

Other Finder methods

where(conditions)

order example Article.order(“title ASC”)

limit example Article.limit(1) example Article.order(“title DESC”).limit(2)

joins

includes

 

Default Scope

class Category < ActiveRecord::Base

attr_accessible :name
has_and_belongs_to_many :articles

default_scope order(‘categories.name’) // you can pass any finder method to default_scope

end

Random! – EXIT rails console!! – Cntrl D

more scope examples for your model

scope :published, where(“articles.published_at IS NOT NULL”)
scope :draft, where(“articles.published_at IS NULL”)
scope :recent, lambda { published.where(“articles.published_at > ?”, 1.week.ago.to_date)}
scope :where_title, lambda { |term| where(“articles.title LIKE ?”, “%#{term}%”)}

Leave a Reply

You must be logged in to post a comment.