`
hideto
  • 浏览: 2650394 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

每天一剂Rails良药之DRY Up Your ActiveRecord Code With Scoping

    博客分类:
  • Ruby
阅读更多
Rails真的是在搜肠刮肚挖空心思想方设法的给代码减肥瘦身,这次我们来看看with_scope方法
class PostsController < ApplicationController
  before_filter :scope_posts_to_user

  def show
    @posts = Post.find(:all)
  end

  def create
    @post = Post.create(params[:post])
  end

  private

  def scope_posts_to_user
    Post.with_scope({
      :find => {:conditions => ['user_id = ?', @user.id]},
      :create => {:user =. @user}
    }) { yield }
  end

上面的yield块也可以用来find或create Post
with_scope方法还可以嵌套scope,详见http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001024
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics