Rails - 多态关联有很多关系 - 索引值
Rails - Polymorphic Associations with has many relationship - index values
我有组织模型和 Package_ip。
协会是:
组织
has_many :ips, as: :ipable, class_name: Package::Ip
accepts_nested_attributes_for :ips, reject_if: :all_blank, allow_destroy: true
包::Ip
belongs_to :ipable, :polymorphic => true, optional: true, inverse_of: :ip
Package_ip的table有:
create_table "package_ips", force: :cascade do |t|
t.string "identifier"
t.text "description"
t.text "conditions"
t.integer "ipable_id"
t.string "ipable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "title"
t.string "status"
t.string "classification"
t.index ["ipable_type", "ipable_id"], name: "index_package_ips_on_ipable_type_and_ipable_id", unique: true, using: :btree
end
我的 objective 供组织创建 package_ip 的多个实例。
但是我对索引的工作方式有疑问。如果我想创建 package_ip 的第二个实例,我会收到一条错误消息,指出索引值不再唯一。
我可以从索引中删除唯一约束吗?我意识到 ipable_ip 将成为 organisation.id,而 ipable_type 将成为父 class(组织)。我不明白为什么这需要是独一无二的。但也许我错过了有关多态关联和对索引的依赖的一些信息。
是的,此限制来自您的业务逻辑,而不是 rails 中内置的。
Rails 应该允许您删除唯一约束,确保您的业务逻辑可以安全地处理这个是明智的。
您可能有这样的代码:
foo_ip org.ips.where(type: "foo").first
这将希望存在于命名范围内(如果存在的话)。
评论后更新:
大概您正在使用 IP 作为 "Intellectual Properties".
假设你有
class Song < Package::Ip
end
class ThemeSong < Song
end
class Logo < Package::IP
end
您的业务逻辑可能希望组织有一首主题曲或一首徽标。
所以你可能有这样的代码:
theme = org.theme_songs.first
或:
logo = org.logos.first
# Or worse yet
logo = org.ips.where(:type = "Logo").first
因此,虽然 Rails 支持多个 Song
或 Logo
,但请确保您的业务逻辑在某些情况下不只采用第一个。
我有组织模型和 Package_ip。
协会是:
组织
has_many :ips, as: :ipable, class_name: Package::Ip
accepts_nested_attributes_for :ips, reject_if: :all_blank, allow_destroy: true
包::Ip
belongs_to :ipable, :polymorphic => true, optional: true, inverse_of: :ip
Package_ip的table有:
create_table "package_ips", force: :cascade do |t|
t.string "identifier"
t.text "description"
t.text "conditions"
t.integer "ipable_id"
t.string "ipable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "title"
t.string "status"
t.string "classification"
t.index ["ipable_type", "ipable_id"], name: "index_package_ips_on_ipable_type_and_ipable_id", unique: true, using: :btree
end
我的 objective 供组织创建 package_ip 的多个实例。
但是我对索引的工作方式有疑问。如果我想创建 package_ip 的第二个实例,我会收到一条错误消息,指出索引值不再唯一。
我可以从索引中删除唯一约束吗?我意识到 ipable_ip 将成为 organisation.id,而 ipable_type 将成为父 class(组织)。我不明白为什么这需要是独一无二的。但也许我错过了有关多态关联和对索引的依赖的一些信息。
是的,此限制来自您的业务逻辑,而不是 rails 中内置的。 Rails 应该允许您删除唯一约束,确保您的业务逻辑可以安全地处理这个是明智的。
您可能有这样的代码:
foo_ip org.ips.where(type: "foo").first
这将希望存在于命名范围内(如果存在的话)。
评论后更新: 大概您正在使用 IP 作为 "Intellectual Properties".
假设你有
class Song < Package::Ip
end
class ThemeSong < Song
end
class Logo < Package::IP
end
您的业务逻辑可能希望组织有一首主题曲或一首徽标。
所以你可能有这样的代码:
theme = org.theme_songs.first
或:
logo = org.logos.first
# Or worse yet
logo = org.ips.where(:type = "Logo").first
因此,虽然 Rails 支持多个 Song
或 Logo
,但请确保您的业务逻辑在某些情况下不只采用第一个。