我有模板和模板版本。模板可以有多個template_versions,但是在任何給定的時間只有一個活動的template_version。我有以下兩種模式:Ruby On Rails:一對多一對一
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
這是至關重要的一個模板只能有一個活動template_version,這也就是爲什麼關鍵active_template是模板模型。這一切似乎罰款,直到我在Rails控制檯測試:
t = Template.new()
tv = TemplateVersion.new()
t.active_version = tv
t.save
version = t.active_version //returns version
version.template_id //returns nil
模板知道其活動template_version,但問題是,template_version不知道它屬於哪個模板。我猜這是因爲在插入數據庫時,創建了template_version以獲取將模板與模板關聯的id,然後必須保存該模板才能返回模板ID以填充模板版本。
有沒有辦法完成這一切?
您是否使用':foreign_key'嘗試過類似http://guides.rubyonrails.org/association_basics.html#self-joins? –
@Lucas - 給定的模型不需要關係到自我。你是在暗示一種不同的模式? – jbodily