3

The Rails guides state that a scope can be called on an association. But then further on, it states that the scoped method, which returns an ActiveRecord::Relation object, "may come in handy...on associations". If a scope can be called on an association, what additional functionality does scoped provide?

4

1 に答える 1

2

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?
于 2013-02-21T16:18:05.833 に答える