I have two models below. They can be explained as follows:
A report has a report_detail (which determines start/end months). Many reports can have the same report detail, but no two report details can be the same.
class Report < ActiveRecord::Base
# attr: name :: String
# attr: report_detail_id :: Integer
belongs_to :report_detail
accepts_nested_attributes_for :report_detail
end
class ReportDetail < ActiveRecord::Base
# attr: duration :: Integer
# attr: starting_month :: Integer
# attr: offset :: Integer
end
I have a unique constraint on an index on ReportDetail for [:duration, :starting_month, :offset]
What I'm trying to accomplish is this: If a new Report has ReportDetail that has a unique combination attrs (:duration, :starting_month, :offset), create the new ReportDetail and save as normal. If a report has a ReportDetail whereby an existing ReportDetail has the same attributes, associate the report's detail with this ReportDetail and save report.
I got this to work by aliasing the setter on report_detail=
using a ReportDetail.find_or_create_by...
but it's ugly (and it also creates unnecessary ReportDetail entries just by instantiating new Reports with the detail attributes, and for some reason i couldn't get the save to work properly using .find_or_initialize_by...
). I also tried a before_save
on the ReportDetail to say, if I match something else, set self
to that something else. Apparently you can't set self like that.
Any thought on the best way to go about this?
see this gist for my current setter overwrite with alias