原创作者: hideto   阅读:1456次   评论:0条   更新时间:2011-05-26    
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
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics