Rails真的是在搜肠刮肚挖空心思想方设法的给代码减肥瘦身,这次我们来看看with_scope方法
[code]
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
[/code]
上面的yield块也可以用来find或create Post
with_scope方法还可以嵌套scope,详见[url]http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001024[/url]
[code]
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
[/code]
上面的yield块也可以用来find或create Post
with_scope方法还可以嵌套scope,详见[url]http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M001024[/url]
本文探讨了Rails框架中with_scope方法的应用,该方法通过精简代码来优化Post控制器的操作,如显示和创建Post。文章提供了具体的代码示例,展示了如何使用with_scope来指定条件并作用于find和create操作。
3114

被折叠的 条评论
为什么被折叠?



