diff options
Diffstat (limited to 'railties/guides/source/active_record_querying.textile')
-rw-r--r-- | railties/guides/source/active_record_querying.textile | 34 |
1 files changed, 29 insertions, 5 deletions
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile index 8517f6fb19..21bbc64255 100644 --- a/railties/guides/source/active_record_querying.textile +++ b/railties/guides/source/active_record_querying.textile @@ -404,6 +404,8 @@ Or ordering by multiple fields: <ruby> Client.order("orders_count ASC, created_at DESC") +# OR +Client.order("orders_count ASC", "created_at DESC") </ruby> h3. Selecting Specific Fields @@ -606,9 +608,33 @@ SELECT * FROM clients WHERE orders_count > 10 ORDER BY clients.id DESC This method accepts *no* arguments. +h3. Null Relation + +The +none+ method returns a chainable relation with no records. Any subsequent conditions chained to the returned relation will continue generating empty relations. This is useful in scenarios where you need a chainable response to a method or a scope that could return zero results. + +<ruby> +Post.none # returns an empty Relation and fires no queries. +</ruby> + +<ruby> +# The visible_posts method below is expected to return a Relation. +@posts = current_user.visible_posts.where(:name => params[:name]) + +def visible_posts + case role + when 'Country Manager' + Post.where(:country => country) + when 'Reviewer' + Post.published + when 'Bad User' + Post.none # => returning [] or nil breaks the caller code in this case + end +end +</ruby> + h3. Readonly Objects -Active Record provides +readonly+ method on a relation to explicitly disallow modification or deletion of any of the returned object. Any attempt to alter or destroy a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. +Active Record provides +readonly+ method on a relation to explicitly disallow modification of any of the returned objects. Any attempt to alter a readonly record will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. <ruby> client = Client.readonly.first @@ -648,15 +674,13 @@ c2.save # Raises an ActiveRecord::StaleObjectError You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, or otherwise apply the business logic needed to resolve the conflict. -NOTE: You must ensure that your database schema defaults the +lock_version+ column to +0+. - This behavior can be turned off by setting <tt>ActiveRecord::Base.lock_optimistically = false</tt>. -To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class method called +set_locking_column+: +To override the name of the +lock_version+ column, +ActiveRecord::Base+ provides a class attribute called +locking_column+: <ruby> class Client < ActiveRecord::Base - set_locking_column :lock_client_column + self.locking_column = :lock_client_column end </ruby> |