3

我有模板和模板版本。模板可以有多個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以填充模板版本。

有沒有辦法完成這一切?

+0

您是否使用':foreign_key'嘗試過類似http://guides.rubyonrails.org/association_basics.html#self-joins? –

+0

@Lucas - 給定的模型不需要關係到自我。你是在暗示一種不同的模式? – jbodily

回答

0

不知道這個,但你可以嘗試以下操作:

t = Template.new() 
tv = TemplateVersion.new() 
tv.save 
t.active_version = tv 
t.save 

或可能

t = Template.new() 
tv = TemplateVersion.create() 
t.active_version = tv 
t.save 

我相信如果你使用create你不需要save

1

當前設置的問題是您爲TemplateVersion定義了兩個「模板」方法。如果我有一個電視對象,tv.template可能是has_one或belongs_to模板,ActiveRecord不知道哪個。我不確定你是否能以某種方式別名。

一種解決方法:添加一個「活動」欄,即可TemplateVersion模型和驗證,只有一個活躍TemplateVersion

class Template < ActiveRecord::Base 
    has_many :template_versions, :class_name => 'TemplateVersion' 
    has_one :active_version, :class_name => 'TemplateVersion', :conditions => ['active = ?', true] 
end 

class TemplateVersion < ActiveRecord::Base 
    attr_accessible :template_id, :active 
    belongs_to :template 
    validates :only_one_active 

    def only_one_active 
     errors.add(:base, "Only one active version per template") if self.active == true and TemplateVersion.where(:active => true, :template_id => self.template_id).count > 0 
    end 

end 

然後,您可以訪問活動版本t.active_version,但要設置活動版本,需要在TemplateVersion上進行更新。