Rails真的是在搜腸刮肚挖空心思想方設法的給代碼減肥瘦身,這次我們來看看with_scope方法
上面的yield塊也可以用來find或create Post
with_scope方法還可以嵌套scope,詳見http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001024
- 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
安徽新華電腦學校專業職業規劃師為你提供更多幫助【在線咨詢】