#202 Active Record Queries in Rails 3
Feb 22, 2010 | 10 minutes | Rails 3.0, Active Record
Rails 3 introduces a new query interface for performing finds in Active Record. See how it works along with the changes in named scopes.
- Download:
- source codeProject Files in Zip (99.6 KB)
- mp4Full Size H.264 Video (15.1 MB)
- m4vSmaller H.264 Video (10.7 MB)
- webmFull Size VP8 Video (31.6 MB)
- ogvFull Size Theora Video (24 MB)
Resources
ruby
# Article.find(:all, :order => "published_at desc", :limit => 10)
Article.order("published_at desc").limit(10)
# Article.find(:all, :conditions => ["published_at <= ?", Time.now], :include => :comments)
Article.where("published_at <= ?", Time.now).includes(:comments)
# Article.find(:first, :order => "published_at desc")
Article.order("published_at").last
# Article.find(:all, :order => "published_at desc", :limit => 10) Article.order("published_at desc").limit(10) # Article.find(:all, :conditions => ["published_at <= ?", Time.now], :include => :comments) Article.where("published_at <= ?", Time.now).includes(:comments) # Article.find(:first, :order => "published_at desc") Article.order("published_at").last
rails console
Article.all
articles = Article.order("name")
articles.all
articles.first
Article.recent.all
puts Article.recent.to_sql
Article.all articles = Article.order("name") articles.all articles.first Article.recent.all puts Article.recent.to_sql
articles_controller.rb
@articles = Article.order("name")
if params[:hidden]
@articles = @articles.where(:hidden => (params[:hidden] == "1"))
end
@articles = Article.order("name") if params[:hidden] @articles = @articles.where(:hidden => (params[:hidden] == "1")) end
models/active_record.rb
scope :visible, where("hidden != ?", true)
scope :published, lambda { where("published_at <= ?", Time.zone.now) }
scope :recent, visible.published.order("published_at desc")
scope :visible, where("hidden != ?", true) scope :published, lambda { where("published_at <= ?", Time.zone.now) } scope :recent, visible.published.order("published_at desc")

