has_many_through_association.rb 10.6 KB
Newer Older
1 2
module ActiveRecord
  module Associations
3
    class HasManyThroughAssociation < HasManyAssociation #:nodoc:
4
      def initialize(owner, reflection)
5
        reflection.check_validity!
6
        super
7 8
      end

9
      alias_method :new, :build
10 11

      def create!(attrs = nil)
12
        transaction do
13
          self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.create_association! } : @reflection.create_association!)
14
          object
15 16 17
        end
      end

18
      def create(attrs = nil)
19
        transaction do
20
          self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.create_association } : @reflection.create_association)
21 22 23 24
          object
        end
      end

25 26 27 28
      # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and
      # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero
      # and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length.
      def size
29 30 31
        return @owner.send(:read_attribute, cached_counter_attribute_name) if has_cached_counter?
        return @target.size if loaded?
        return count
32
      end
33
      
34
      protected
35 36 37 38 39 40 41 42
        def target_reflection_has_associated_record?
          if @reflection.through_reflection.macro == :belongs_to && @owner[@reflection.through_reflection.primary_key_name].blank?
            false
          else
            true
          end
        end

43 44 45 46 47 48 49
        def construct_find_options!(options)
          options[:select]  = construct_select(options[:select])
          options[:from]  ||= construct_from
          options[:joins]   = construct_joins(options[:joins])
          options[:include] = @reflection.source_reflection.options[:include] if options[:include].nil?
        end
        
50
        def insert_record(record, force = true, validate = true)
51 52 53 54
          if record.new_record?
            if force
              record.save!
            else
55
              return false unless record.save(validate)
56 57
            end
          end
58 59 60
          through_reflection = @reflection.through_reflection
          klass = through_reflection.klass
          @owner.send(@reflection.through_reflection.name).proxy_target << klass.send(:with_scope, :create => construct_join_attributes(record)) { through_reflection.create_association! }
61 62 63 64 65 66 67 68 69 70
        end

        # TODO - add dependent option support
        def delete_records(records)
          klass = @reflection.through_reflection.klass
          records.each do |associate|
            klass.delete_all(construct_join_attributes(associate))
          end
        end

71
        def find_target
72
          return [] unless target_reflection_has_associated_record?
73
          @reflection.klass.find(:all,
74
            :select     => construct_select,
75 76
            :conditions => construct_conditions,
            :from       => construct_from,
77
            :joins      => construct_joins,
78
            :order      => @reflection.options[:order],
79
            :limit      => @reflection.options[:limit],
80
            :group      => @reflection.options[:group],
81
            :readonly   => @reflection.options[:readonly],
82
            :include    => @reflection.options[:include] || @reflection.source_reflection.options[:include]
83 84 85
          )
        end

86 87
        # Construct attributes for associate pointing to owner.
        def construct_owner_attributes(reflection)
88 89 90 91 92 93 94 95
          if as = reflection.options[:as]
            { "#{as}_id" => @owner.id,
              "#{as}_type" => @owner.class.base_class.name.to_s }
          else
            { reflection.primary_key_name => @owner.id }
          end
        end

96 97
        # Construct attributes for :through pointing to owner and associate.
        def construct_join_attributes(associate)
98 99
          # TODO: revist this to allow it for deletion, supposing dependent option is supported
          raise ActiveRecord::HasManyThroughCantAssociateThroughHasManyReflection.new(@owner, @reflection) if @reflection.source_reflection.macro == :has_many
100 101 102
          join_attributes = construct_owner_attributes(@reflection.through_reflection).merge(@reflection.source_reflection.primary_key_name => associate.id)
          if @reflection.options[:source_type]
            join_attributes.merge!(@reflection.source_reflection.options[:foreign_type] => associate.class.base_class.name.to_s)
103
          end
104
          join_attributes
105 106 107 108
        end

        # Associate attributes pointing to owner, quoted.
        def construct_quoted_owner_attributes(reflection)
109
          if as = reflection.options[:as]
110
            { "#{as}_id" => owner_quoted_id,
111
              "#{as}_type" => reflection.klass.quote_value(
112 113
                @owner.class.base_class.name.to_s,
                reflection.klass.columns_hash["#{as}_type"]) }
114 115
          elsif reflection.macro == :belongs_to
            { reflection.klass.primary_key => @owner[reflection.primary_key_name] }
116
          else
117
            { reflection.primary_key_name => owner_quoted_id }
118 119 120
          end
        end

121
        # Build SQL conditions from attributes, qualified by table name.
122
        def construct_conditions
123
          table_name = @reflection.through_reflection.quoted_table_name
124
          conditions = construct_quoted_owner_attributes(@reflection.through_reflection).map do |attr, value|
125
            "#{table_name}.#{attr} = #{value}"
126
          end
127 128
          conditions << sql_conditions if sql_conditions
          "(" + conditions.join(') AND (') + ")"
129 130 131
        end

        def construct_from
132
          @reflection.quoted_table_name
133
        end
134

135
        def construct_select(custom_select = nil)
136 137
          distinct = "DISTINCT " if @reflection.options[:uniq]
          selected = custom_select || @reflection.options[:select] || "#{distinct}#{@reflection.quoted_table_name}.*"
138
        end
139 140

        def construct_joins(custom_joins = nil)
141
          polymorphic_join = nil
142
          if @reflection.source_reflection.macro == :belongs_to
143 144
            reflection_primary_key = @reflection.klass.primary_key
            source_primary_key     = @reflection.source_reflection.primary_key_name
145 146
            if @reflection.options[:source_type]
              polymorphic_join = "AND %s.%s = %s" % [
147
                @reflection.through_reflection.quoted_table_name, "#{@reflection.source_reflection.options[:foreign_type]}",
148 149 150
                @owner.class.quote_value(@reflection.options[:source_type])
              ]
            end
151 152 153
          else
            reflection_primary_key = @reflection.source_reflection.primary_key_name
            source_primary_key     = @reflection.klass.primary_key
154 155
            if @reflection.source_reflection.options[:as]
              polymorphic_join = "AND %s.%s = %s" % [
156
                @reflection.quoted_table_name, "#{@reflection.source_reflection.options[:as]}_type",
157
                @owner.class.quote_value(@reflection.through_reflection.klass.name)
158 159
              ]
            end
160
          end
161

162
          "INNER JOIN %s ON %s.%s = %s.%s %s #{@reflection.options[:joins]} #{custom_joins}" % [
163 164 165
            @reflection.through_reflection.quoted_table_name,
            @reflection.quoted_table_name, reflection_primary_key,
            @reflection.through_reflection.quoted_table_name, source_primary_key,
166
            polymorphic_join
167 168
          ]
        end
169

170
        def construct_scope
171
          { :create => construct_owner_attributes(@reflection),
172 173 174
            :find   => { :from        => construct_from,
                         :conditions  => construct_conditions,
                         :joins       => construct_joins,
175
                         :include     => @reflection.options[:include],
176
                         :select      => construct_select,
177
                         :order       => @reflection.options[:order],
178 179 180
                         :limit       => @reflection.options[:limit],
                         :readonly    => @reflection.options[:readonly],
             } }
181
        end
182

183 184 185 186 187
        def construct_sql
          case
            when @reflection.options[:finder_sql]
              @finder_sql = interpolate_sql(@reflection.options[:finder_sql])

188
              @finder_sql = "#{@reflection.quoted_table_name}.#{@reflection.primary_key_name} = #{owner_quoted_id}"
189
              @finder_sql << " AND (#{conditions})" if conditions
190 191
            else
              @finder_sql = construct_conditions
192 193 194 195 196
          end

          if @reflection.options[:counter_sql]
            @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
          elsif @reflection.options[:finder_sql]
197 198
            # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
            @reflection.options[:counter_sql] = @reflection.options[:finder_sql].sub(/SELECT (\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
199 200 201 202 203
            @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
          else
            @counter_sql = @finder_sql
          end
        end
204

205
        def conditions
206 207 208 209 210 211
          @conditions = build_conditions unless defined?(@conditions)
          @conditions
        end

        def build_conditions
          association_conditions = @reflection.options[:conditions]
212
          through_conditions = build_through_conditions
213 214 215 216 217 218
          source_conditions = @reflection.source_reflection.options[:conditions]
          uses_sti = !@reflection.through_reflection.klass.descends_from_active_record?

          if association_conditions || through_conditions || source_conditions || uses_sti
            all = []

219
            [association_conditions, source_conditions].each do |conditions|
220 221 222
              all << interpolate_sql(sanitize_sql(conditions)) if conditions
            end

223
            all << through_conditions  if through_conditions
224 225 226 227 228 229
            all << build_sti_condition if uses_sti

            all.map { |sql| "(#{sql})" } * ' AND '
          end
        end

230 231 232 233 234 235 236 237 238 239 240
        def build_through_conditions
          conditions = @reflection.through_reflection.options[:conditions]
          if conditions.is_a?(Hash)
            interpolate_sql(sanitize_sql(conditions)).gsub(
              @reflection.quoted_table_name,
              @reflection.through_reflection.quoted_table_name)
          elsif conditions
            interpolate_sql(sanitize_sql(conditions))
          end
        end
        
241
        def build_sti_condition
242
          @reflection.through_reflection.klass.send(:type_condition)
243
        end
244

245
        alias_method :sql_conditions, :conditions
246 247 248 249 250 251 252 253

        def has_cached_counter?
          @owner.attribute_present?(cached_counter_attribute_name)
        end

        def cached_counter_attribute_name
          "#{@reflection.name}_count"
        end
254 255 256
    end
  end
end