Module: OnForm::Saving
- Included in:
- Form
- Defined in:
- lib/on_form/saving.rb
Class Method Summary collapse
Instance Method Summary collapse
- #save(validate: true) ⇒ Object
- #save!(validate: true) ⇒ Object
- #transaction(&block) ⇒ Object
- #update(attributes) ⇒ Object (also: #update_attributes)
- #update!(attributes) ⇒ Object (also: #update_attributes!)
Class Method Details
.included(base) ⇒ Object
3 4 5 |
# File 'lib/on_form/saving.rb', line 3 def self.included(base) base.define_model_callbacks :save end |
Instance Method Details
#save(validate: true) ⇒ Object
42 43 44 45 46 |
# File 'lib/on_form/saving.rb', line 42 def save(validate: true) save!(validate: validate) rescue ActiveRecord::RecordInvalid, ActiveModel::ValidationError false end |
#save!(validate: true) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/on_form/saving.rb', line 17 def save!(validate: true) transaction do reset_errors if validate run_validations! if !errors.empty? if form_errors? raise ActiveModel::ValidationError, self else raise ActiveRecord::RecordInvalid, self end end end run_callbacks :save do # we pass (validate: false) to avoid running the validations a second time, but we use save! to get the RecordNotFound behavior backing_model_instances.each { |backing_model| backing_model.save!(validate: false) } save_child_forms(validate: false) end end true end |
#transaction(&block) ⇒ Object
7 8 9 10 11 12 13 14 15 |
# File 'lib/on_form/saving.rb', line 7 def transaction(&block) backing_models = backing_model_instances if backing_models.empty? with_transactions([ActiveRecord::Base], &block) else with_transactions(backing_model_instances, &block) end end |
#update(attributes) ⇒ Object Also known as: update_attributes
48 49 50 51 52 53 |
# File 'lib/on_form/saving.rb', line 48 def update(attributes) transaction do self.attributes = attributes save end end |
#update!(attributes) ⇒ Object Also known as: update_attributes!
55 56 57 58 59 60 |
# File 'lib/on_form/saving.rb', line 55 def update!(attributes) transaction do self.attributes = attributes save! end end |