3

我有模板和模板版本。一个模板可以有多个 template_version,但在任何给定时间只有一个活动的 template_version。我有以下两个模型:

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 以获取与模板关联的 id,然后必须保存它以交回模板 id 以填充模板版本。

有没有办法完成这一切?

4

2 回答 2

1

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

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

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.

于 2012-10-24T21:04:37.387 回答
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

于 2012-10-24T00:45:46.483 回答