3
Rails guides指出可以在關聯上調用作用域。但後來further on,它指出,scoped
方法,它返回一個ActiveRecord::Relation
對象,「可能派上用場......關聯」。如果可以在關聯上調用作用域,那麼scoped
還提供了哪些其他功能?爲什麼Rails指南建議在關聯上使用範圍方法?
Rails guides指出可以在關聯上調用作用域。但後來further on,它指出,scoped
方法,它返回一個ActiveRecord::Relation
對象,「可能派上用場......關聯」。如果可以在關聯上調用作用域,那麼scoped
還提供了哪些其他功能?爲什麼Rails指南建議在關聯上使用範圍方法?
scoped
返回匿名範圍。從API文檔:
當程序生成複雜查詢時,匿名範圍往往很有用,因爲在第一類對象周圍傳遞中間值(範圍)時非常方便。
這裏的例子:
posts = Post.scoped
posts.size # Fires "select count(*) from posts" and returns the count
posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects
fruits = Fruit.scoped
fruits = fruits.where(:color => 'red') if options[:red_only]
fruits = fruits.limit(10) if limited?