Rails 2.1推出了令人心癢癢的功能喔!讓我感覺到Rails更迷人更方便了>///<
不過我就先說兩個部份吧?

Find:
呵呵,find應該很多人都會用到吧?
這次做了點小更動呢!

假設我有一個Project Model...
  • Project.all #=> Project.find(:all)
  • Project.first #=> Project.find(:first)
接著是新增的喔!
  • Project.find(:last) #=> Project.find(:first, :order => "id DESC")
  • Project.last #=> Project.find(:last)
如何?取得資料更容易了對吧?
Named Scope:
至於這個則是從一個叫做has_finder的gem改過來的一個功能
這個功能被改過來後就改名為named_scope
假設我有一個Model叫做Article...
我想要取得所有public為true的文章,我通常會寫成
Article.find(:all, :conditions => ["public = true"])
或者是
Article.find_by_public(true)
但是透過named_scope...
# In Article.rb
class Article < ActiveRecord::Base
  named_scope :published, :conditions => { :public => true }
end

# In articles_controller.rb
class ArticlesController < ApplicationController
  def index
    @articles = Article.published
  end
end
如此即可!

arrow
arrow
    全站熱搜

    hechian 發表在 痞客邦 留言(0) 人氣()