I have templates and template versions. A template can have many template_versions, but only one active template_version at any given time. I have the following two models:
class Template < ActiveRecord:Base
has_many :template_versions, :class_name => 'TemplateVersion'
belongs_to :active_version, :class_name => 'TemplateVersion'
end
class TemplateVersion < ActiveRecord:Base
belongs_to :template
has_one :template
end
It’s critical that a template only have one active template_version, which is why the key to the active_template is on the template model. This all seems fine until I test it in a rails console:
t = Template.new()
tv = TemplateVersion.new()
t.active_version = tv
t.save
version = t.active_version //returns version
version.template_id //returns nil
The template knows about its active template_version, but the problem is that the template_version doesn’t know what template it belongs to. I’m guessing this is because on the insert to the DB, the template_version is created to get the id to associate the template with, which would then have to be saved to hand back the template id to populate the template version.
Is there a way of accomplishing all this?
The problem with your current setup is you’ve defined two “template” methods for TemplateVersion. If I have a tv object, tv.template could be the has_one or belongs_to template, ActiveRecord doesn’t know which. I’m not sure if you can alias those somehow.
A workaround: add an “active” column to your TemplateVersion model and validate there’s only one active TemplateVersion
You can then access the active version as t.active_version, but to set the active version you’d need to make that update on the the TemplateVersion.