Вопрос

How do I create a polymorphic relation using the MySQL Workbench tool? I want to be able to handle something like what Rails gives me with:

class Example < ActiveRecord::Base
  belongs_to :someone, polymorphic: true
end

class PolyOne < ActiveRecord::Base
  has_many :examples, as: :someone
end

class PolyTwo < ActiveRecord::Base
  has_many :examples, as: :someone
end
Это было полезно?

Решение

If you utilize the "Place a relationship using existing columns," the icon with the 1:N and dropper, you'll be able to accomplish this task. In the examples table (Rails always pluralizes), make sure you have two columns: someone_id and someone_type. In the polymorphic tables, you should already have an id column. Then, you choose the tool mentioned at first (1:N with dropper) and click on someone_id followed by the id of the polymorphic table. This will create a new 1:N relationship between those two fields without inserting any new fields into the tables. Repeat this process for each connected polymorphic table. It will then represent the polymorphic relationship that Rails uses. If you are trying to mimic this on your own without Rails, you'll need to be sure to set the someone_id and someone_type appropriately so that you can follow the polymorphic relationship properly.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top