亚洲成人一区在线观看_天堂网www_国产精品久久9_中文在线播放_伊人天天_久久精品久久久精品美女

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

每天一劑Rails良藥之DRY Up Your ActiveRecord Code With Scoping
2010-01-14 07:02:23  作者:  來源:
Rails真的是在搜腸刮肚挖空心思想方設(shè)法的給代碼減肥瘦身,這次我們來看看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

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

抢占助学金名额