aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_relation/relations/update.rb
blob: a51f248866864fd236da4f9e128058bcf2c7f201 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module ActiveRelation
  class Update < Writing
    attr_reader :assignments

    def initialize(relation, assignments)
      @relation, @assignments = relation, assignments
    end

    def to_sql(strategy = nil)
      [
        "UPDATE #{table_sql} SET",
        assignments.inject("") do |assignments, (attribute, value)| 
          assignments << " #{attribute.to_sql} = #{value.to_sql}"
        end,
        ("WHERE #{selects.collect(&:to_sql).join('\n\tAND ')}" unless selects.blank?)
      ].join("\n")
    end
    
    def call(connection = engine.connection)
      connection.update(to_sql)
    end
    
    def ==(other)
      self.class  == other.class    and
      relation    == other.relation and
      assignments == other.assignments
    end
  end
end