In memory (static) has_many for ActiveRecord
This replicates something like a has_many
in ActiveRecord but the assosiated
records are hardcoded statically in the model, not persisted to the database.
By sticking
to an API similar to a real has_many
we could more easily replace this is the future with
a persisted records.
First add a foreign key column:
add_column :recipients, :rejection_cause_id, :string
I had choosen to use a string as the primary key for the model.
Add a method to return the associated records:
class Recipient < ActiveRecord::Base
def rejection_cause
RejectionCause.find(rejection_cause_id)
end
end
And then a new model which ducktypes like ActiveRecord.
class Recipient
RejectionCause = Struct.new(:id, :name) do
def self.find(id)
all.find { |it| it.id == id }
end
def self.all
[
new('CS', 'Competing Studies'),
new('IR', 'Insufficient Resource'),
new('NPI', 'No PI Interest'),
new('NRG', 'No Reason Given'),
new('PP', 'Patient Population'),
new('SC', 'Safety Concerns'),
new('NTN', 'Not Treated at NUH')
]
end
end
end
And finally add an input to a form.
= form.input :rejection_cause_id, collection: Recipient::RejectionCauses.all
You could expand this further if need be, for example by adding
rejection_cause=(new_rejection_cause)
but I would stick to the smallest
surface area as strictly required.