国产一区二区精品久久_蜜桃狠狠狠狠狠狠狠狠狠_午夜视频精品_激情都市一区二区

當前位置:首頁 > 網站舊欄目 > 學習園地 > 設計軟件教程 > 每天一劑Rails良藥之DRY Up Your ActiveRecord Code With Scoping

每天一劑Rails良藥之DRY Up Your ActiveRecord Code With Scoping
2010-01-14 07:02:23  作者:  來源:
Rails真的是在搜腸刮肚挖空心思想方設法的給代碼減肥瘦身,這次我們來看看with_scope方法
Java代碼 復制代碼
  1. class PostsController < ApplicationController   
  2.   before_filter :scope_posts_to_user   
  3.   
  4.   def show   
  5.     @posts = Post.find(:all)   
  6.   end   
  7.   
  8.   def create   
  9.     @post = Post.create(params[:post])   
  10.   end   
  11.   
  12.   private  
  13.   
  14.   def scope_posts_to_user   
  15.     Post.with_scope({   
  16.       :find => {:conditions => ['user_id = ?'@user.id]},   
  17.       :create => {:user =. @user}   
  18.     }) { yield }   
  19.   end  

上面的yield塊也可以用來find或create Post
with_scope方法還可以嵌套scope,詳見http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001024

安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢