Class: UpdateAllScope::UpdateAllScope
- Inherits:
-
Object
- Object
- UpdateAllScope::UpdateAllScope
- Defined in:
- lib/update_all_scope/update_all_scope.rb
Constant Summary collapse
- AREL_SUPPORT_JOIN_TABLE =
Gem::Version.new(Arel::VERSION) >= Gem::Version.new('10')
Instance Method Summary collapse
- #do_query! ⇒ Object
-
#initialize(model: nil, relation: nil) ⇒ UpdateAllScope
constructor
A new instance of UpdateAllScope.
- #klass ⇒ Object
- #to_arel ⇒ Object
- #to_sql ⇒ Object
- #update(query, *binding_values) ⇒ Object
- #updates_as_string ⇒ Object
- #where(*args) ⇒ Object
Constructor Details
#initialize(model: nil, relation: nil) ⇒ UpdateAllScope
Returns a new instance of UpdateAllScope.
8 9 10 11 |
# File 'lib/update_all_scope/update_all_scope.rb', line 8 def initialize(model: nil, relation: nil) @queries = [] @relation = relation || model.class.where(id: model.id) end |
Instance Method Details
#do_query! ⇒ Object
24 25 26 27 |
# File 'lib/update_all_scope/update_all_scope.rb', line 24 def do_query! return 0 if @queries.empty? return @relation.update_all(updates_as_string) end |
#klass ⇒ Object
33 34 35 |
# File 'lib/update_all_scope/update_all_scope.rb', line 33 def klass @relation.klass end |
#to_arel ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/update_all_scope/update_all_scope.rb', line 38 def to_arel if @relation.eager_loading? scope = UpdateAllScope.new(model: model, relation: @relation.apply_join_dependency) return scope.update(updates_as_string).to_update_manager end stmt = new_arel_update_manager stmt.set Arel.sql(klass.send(:sanitize_sql_for_assignment, updates_as_string)) stmt.table(stmt_table) stmt.key = arel_attribute(@relation.primary_key) if should_use_join_to_update? join_to_update(klass.connection, stmt, stmt.key) else stmt.take(@relation.arel.limit) stmt.order(*@relation.arel.orders) stmt.wheres = @relation.arel.constraints end return stmt end |
#to_sql ⇒ Object
61 62 63 64 65 66 |
# File 'lib/update_all_scope/update_all_scope.rb', line 61 def to_sql connection = klass.connection sql, binds = to_sql_and_binds(connection, to_arel) type_casted_binds(connection, binds).each_with_index{|var, idx| sql = sql.gsub("$#{idx + 1}", connection.quote(var)) } return sql end |
#update(query, *binding_values) ⇒ Object
18 19 20 21 22 |
# File 'lib/update_all_scope/update_all_scope.rb', line 18 def update(query, *binding_values) args = binding_values.size > 0 ? [[query, *binding_values]] : [query] @queries << klass.send(:sanitize_sql_for_assignment, *args) return self end |
#updates_as_string ⇒ Object
29 30 31 |
# File 'lib/update_all_scope/update_all_scope.rb', line 29 def updates_as_string @queries.join(',') end |
#where(*args) ⇒ Object
13 14 15 16 |
# File 'lib/update_all_scope/update_all_scope.rb', line 13 def where(*args) @relation = @relation.where(*args) return self end |