简体   繁体   中英

Rails Delegated Types Migration

I'm trying to use the Rails 6.1 DelegatedType feature , but I'm not sure what the migrations should look like for their example:

class Entry < ApplicationRecord
  delegated_type :entryable, types: %w[ Message Comment ]
  delegate :title, to: :entryable
end

class Message < ApplicationRecord
  def title
    subject
  end
end

class Comment < ApplicationRecord
  def title
    content.truncate(20)
  end
end

Would you use t.belongs_to :entry in the message and comment migration?

The "delegating fields" (which are the same as polymorphic entity_type, entity_id) should be on the delegating model. It uses the same polymorphism mechanism under the hood.

So on your entries table:

def change
  create_table :entries do |t|
    t.references :entryable, polymorphic: true
    t.timestamps
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM