Ruby on rails 如何在Rails 4+;
我有当前的模型结构Ruby on rails 如何在Rails 4+;,ruby-on-rails,ruby-on-rails-4,activerecord,activemodel,Ruby On Rails,Ruby On Rails 4,Activerecord,Activemodel,我有当前的模型结构 publisher --------- has_many :digest_templates has_one :active_template digest_templates --------- belongs_to :publisher, optional: true 数据库结构为: publishers --------- t.string :name t.string :permalink t.string :api_key t.string :domain t.
publisher
---------
has_many :digest_templates
has_one :active_template
digest_templates
---------
belongs_to :publisher, optional: true
数据库结构为:
publishers
---------
t.string :name
t.string :permalink
t.string :api_key
t.string :domain
t.reference :digest_template, index: true, foreign_key: true
digest_templates
---------
t.text :html
t.text :text
t.references :publisher, index: true, foreign_key: true
t.boolean :global, default: false # this is for internally developed templates
在任何给定时间,发布者都可以有一个活动模板,但可以为自己创建任意数量的自定义模板。我想这样做,以便可以进行以下调用:
Publisher.templates
和Publisher.active\u模板
主要问题是,我在同一个表中有全局模板和用户创建的模板。是否有可能使其与此体系结构一起工作?或者有更好的方法吗?对于最简单的情况,我建议在
摘要\u模板
中添加类型为布尔的列活动
,并添加如下验证:
validate_uniqueness_of :active, if: :active_template?
有了这行代码,您一次只能有一个active
等于true
的模板。它将为您节省一张桌子
现在,您只需要定义一个关系,如has\u many:templates
,您可以定义实例方法来获取活动模板 几个问题:
您不需要t.references:digest\u template
在您的publisher
表中(如果有许多
,则所有外键都将在关联的表中,该表为)
您尚未在数据库中定义模板是否为“活动”模板
我看到的最大问题是无法定义模板是否为“活动”。我想在您的发布者
表中添加一个名为活动的bool列:
# db/migrate/add_active_to_templates______.rb
class DigestTemplate < ActiveRecord::Migration
change_table :templates do |t|
t.boolean :active, default: :false
end
end
这将允许您拨打:
#app/models/publisher.rb
class Publisher < ActiveRecord::Base
has_many :digest_templates
def active_template
digest_templates.find_by active: true
end
end
活动模板同时也是摘要模板?如果是这样,您将在数据库中保存相同的数据两次。@ArslanAli活动的\u模板只是对活动的摘要\u模板的ID引用。似乎这样可以工作。你遇到了什么问题?publisher.templates
应该返回什么?它是否应该简单地返回来自“has\u many
关系”的所有关联摘要\u模板
?如何指定活动模板?当发布者将默认模板设置为全局模板时,这不起作用。他们不拥有那个模板,所以并没有办法判断。所以模板在两个方面属于用户:1)用户可以是该模板的所有者;2) 用户可以将该模板作为其默认模板。对吧?对。然而,还有一件事:当用户第一次生成时,他们会被分配一个名为global
(换句话说,它对所有用户都是可访问的)的默认模板,就像Arslan的情况一样,这基本上是正确的,除了存在全局可访问的模板(其中global
设置为true)。这些是所有用户都可以访问的默认模板。因此,简单地将active
设置为true在这种情况下不起作用。
#app/models/publisher.rb
class Publisher < ActiveRecord::Base
has_many :digest_templates
def active_template
digest_templates.find_by active: true
end
end
@publisher = Publisher.find params[:id]
@publisher.digest_templates #-> returns all (including active)
@publisher.active_template #-> returns only active