Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# report.rb
# Aliased below. This will check for existing ReportDetail with matching attributes (all of them)
# And if it exists, set the ID, otherwise, set the report_period_detail object using the original method
# Not sure if there is some Railsy way of doing this...
def report_detail_with_find(attrs)
report_detail = ReportDetail.find_or_create_by_duration_and_display_duration_and_starting_month_and_period_offset(attrs[:duration],attrs[:display_duration],attrs[:starting_month],attrs[:period_offset])
# Can't use alias_method_chain as we're overwriting a setter, the = sign messes up naming conventions
# Here we're overwriting the default report_period_detail= method to first check if an exis
alias_method :report_detail_without_find, :report_detail=
alias_method :report_detail=, :report_detail_with_find
# Ensure that if our report_detail has changed, we don't update the original as others might reference this
# So instead, search for existing report_period_detail or create new
def before_update
if report_detail.changed?
# attributes method returns keys as strings, we want symbols
attrs = report_detail.attributes.symbolize_keys # convert strings to symbols
[:id, :created_at, :updated_at].each{ |attr| attrs.delete(attr) } # don't assign old, unecessary attrs to new object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.