maeshimaの日記

メモ書きです

今週のrailscasts - Inherited Resources

いわゆるRails的なアプリケーションを作る時に手抜きが出来るgem。他にもいくつか似たようなgemがあるけど、inherited_resourcesは Rails 3.0 に対応していて、かつ一番新しい感じだそう。

Railscasts - Inherited Resources
ASCIIcasts - “Episode 230 - Inherited Resources”

inherited_resources

bundler経由でinstallすると

  • has_scope
  • responders

の二つの依存しているgemもinstallされる。

class ProductsController < InheritedRecources::Base
end

これだけでproductのCRUDができる。挙動を変更したい場合は普通にオーバライドすればいい。ただ、createした後にindexにリダイレクトしたい場合は下記のように書いたりも出来る。

class ProductsController < InheritedResources::Base  
  def create  
    create! { products_path }  
  end  
end

あとは respond_to にも対応しているし nestしたリソースにも対応している。

class ReviewsController < InheritedRecources::Base
  belongs_to :product
  actions :index, :new, :create
end

has_scope

クエリで sql をいじれる gem。inherited_resources入れる時に自動的に入るみたいだけど、使いたいときは明示的にGemfileに記述が必要みたい。bundlerってそんな仕様なんだっけ?

下記のように has_scope で使える scope を指定。

class ProductsController < InheritedResources::Base  
  respond_to :html, :xml  
    
  has_scope :limit, :default => 3
  
  def create  
    create! { products_path }  
  end  
end

?limit=5 のようなクエリを付けると自動で5件かえってくる。limitとか既存のものだけじゃなくて、scopeで定義したものも定義できる。inherited_resourcesで使う時はとくになにも設定なしで使えるけど、単体で使いたい場合はなんかしなきゃいけないみたい。

flashメッセージの変更

下記のようにi18n用のファイルを編集することで、falshのメッセージを修正することが出来る。

# Sample localization file for English. Add more files in this directory for other locales.  
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.  
  
en:  
  flash:  
    actions:  
      create:  
        notice: "Your {{resource_name}} has been created!"