Skip to content

Instantly share code, notes, and snippets.

@eLafo
Last active June 10, 2019 16:08
Show Gist options
  • Save eLafo/2ce6c2e96af319e714e6010aced92e9e to your computer and use it in GitHub Desktop.
Save eLafo/2ce6c2e96af319e714e6010aced92e9e to your computer and use it in GitHub Desktop.
class Foo
# Do some stuff...
# We want to update a field from another model with a value from this model
after_commit :update_bar_field
# Do more stuff...
private
def update_bar_field
# We want to update Bar#bar_field_2 with the value of Foo#foo_field_2
# Bar and foo are related by bar_field_1 and foo_field_1
# (yes, we might use associations instead, but this is an example ;-) )
Bar.where(bar_field_1: foo_field_1).update(bar_field_2: foo_field_2)
end
end
class Foo
# Do some stuff...
# We want to update a field from another model with a value from this model
after_commit :update_bar_field
# Do more stuff...
private
def update_bar_field
# We want to update Bar#bar_field_2 with the value of Foo#foo_field_2
# Bar and foo are related by bar_field_1 and foo_field_1
# (yes, we might use associations instead, but this is an example ;-) )
Bar.by_bar_field(foo_field_1).update(bar_field_2: Foo.maximum(:foo_field_2)
end
end
class Foo
# Do some stuff...
# We want to update a field from another model with a value from this model
after_commit :update_bar_field
# Do more stuff...
private
def update_bar_field
# We want to update Bar#bar_field_2 with the value of Foo#foo_field_2
# Bar and foo are related by bar_field_1 and foo_field_1
# (yes, we might use associations instead, but this is an example ;-) )
Bar.by_bar_field(foo_field_1).update(bar_field_2: foo_field_2)
end
end
class Bar
# ...
scope :by_bar_field, -> (:bar_field) { where(:bar_field, bar_field) }
# ...
end
class FooCreator
def self.call(foo)
new(foo).call
end
def initialize(foo)
@foo = foo
@bar = Bar.by_bar_field(foo.foo_field_1) # This is a violation of Dependency inversion principle, but this is a topic for a different post ;-)
end
def call
@bar.bar_field_2 = @foo.foo_field_2
Foo.transaction do
@foo.save!
@bar.save!
end
end
end
class Foo
# Do some stuff...
end
class Bar
# ...
scope :by_bar_field, -> (:bar_field) { where(:bar_field, bar_field) }
# ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment