Sha256: 94727e966cb6f24dd7a66b6c339187c3081d6901feb92242e5e795079de607bf

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

module BetterAr
  module AssociationCollection
    # Allows for the same interface as {BetterAr::Relation#first} on association collections
    #
    # example:
    #  User.first.records.first(:level => 2, :order! => :name)
    #
    # @param [Hash]
    #   Optional
    # @returns [ActiveRecord::Base]
    def first(opts = {})
      if opts.empty?
        super
      elsif opts.key?(:conditions)
        super(opts)
      else
        scoped.first(opts)
      end
    end

    # Allows for the same interface as {BetterAr::Relation#count} on association collections
    #
    # example:
    #  User.first.records.count(:level => 2)
    #
    # @param [Hash]
    #   Optional
    # @returns [Integer]
    def count(column_name = nil, count_options = {})
      if column_name.is_a?(Hash)
        count_options = column_name
        column_name = nil
      end

      if count_options.empty?
       super
      elsif count_options.key?(:conditions)
        super(column_name, count_options)
      else
        scope.where(count_options).count
      end
    end
  end
end


ActiveSupport.on_load(:active_record) do
  ActiveRecord::Associations::CollectionAssociation.send(:prepend, BetterAr::AssociationCollection)
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
better_ar-0.2.1 lib/better_ar/association_collection.rb
better_ar-0.2.0 lib/better_ar/association_collection.rb