has_many_through_association.rb 10.7 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 12

      def create!(attrs = nil)
        @reflection.klass.transaction do
S
Steven Soroka 已提交
13
          self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.klass.create! } : @reflection.klass.create!)
14
          object
15 16 17
        end
      end

18 19
      def create(attrs = nil)
        @reflection.klass.transaction do
S
Steven Soroka 已提交
20
          self << (object = attrs ? @reflection.klass.send(:with_scope, :create => attrs) { @reflection.klass.create } : @reflection.klass.create)
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 35 36
      
      def count(*args)
        column_name, options = @reflection.klass.send(:construct_count_options_from_args, *args)
        if @reflection.options[:uniq]
P
Pratik Naik 已提交
37
          # This is needed because 'SELECT count(DISTINCT *)..' is not valid SQL statement.
38
          column_name = "#{@reflection.quoted_table_name}.#{@reflection.klass.primary_key}" if column_name == :all
39 40 41 42
          options.merge!(:distinct => true) 
        end
        @reflection.klass.send(:with_scope, construct_scope) { @reflection.klass.count(column_name, options) } 
      end
43

44
      protected
45 46 47 48 49 50 51
        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
        
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
        def insert_record(record, force=true)
          if record.new_record?
            if force
              record.save!
            else
              return false unless record.save
            end
          end
          klass = @reflection.through_reflection.klass
          @owner.send(@reflection.through_reflection.name).proxy_target << klass.send(:with_scope, :create => construct_join_attributes(record)) { klass.create! }
        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

72
        def find_target
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 110
          if as = reflection.options[:as]
            { "#{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
          else
115 116 117 118
            { reflection.primary_key_name => @owner.quoted_id }
          end
        end

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

        def construct_from
130
          @reflection.quoted_table_name
131
        end
132

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

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

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

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

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

186
              @finder_sql = "#{@reflection.quoted_table_name}.#{@reflection.primary_key_name} = #{@owner.quoted_id}"
187
              @finder_sql << " AND (#{conditions})" if conditions
188 189
            else
              @finder_sql = construct_conditions
190 191 192 193 194
          end

          if @reflection.options[:counter_sql]
            @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
          elsif @reflection.options[:finder_sql]
195 196
            # 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" }
197 198 199 200 201
            @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
          else
            @counter_sql = @finder_sql
          end
        end
202

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

        def build_conditions
          association_conditions = @reflection.options[:conditions]
210
          through_conditions = build_through_conditions
211 212 213 214 215 216
          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 = []

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

221
            all << through_conditions  if through_conditions
222 223 224 225 226 227
            all << build_sti_condition if uses_sti

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

228 229 230 231 232 233 234 235 236 237 238
        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
        
239
        def build_sti_condition
240
          "#{@reflection.through_reflection.quoted_table_name}.#{@reflection.through_reflection.klass.inheritance_column} = #{@reflection.klass.quote_value(@reflection.through_reflection.klass.name.demodulize)}"
241
        end
242

243
        alias_method :sql_conditions, :conditions
244 245 246 247 248 249 250 251

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

        def cached_counter_attribute_name
          "#{@reflection.name}_count"
        end
252 253 254
    end
  end
end