Ruby on Rails Custom Migration Generator

后端 未结 3 1149
走了就别回头了
走了就别回头了 2021-02-06 11:38

I\'m creating a Rails gem that integrates closely with Active Record. The gem requires a number of fields to be defined. For example:

class User < ActiveRecor         


        
3条回答
  •  Happy的楠姐
    2021-02-06 12:42

    Actually if you call

    rails g model profile name:string next:attached
    

    rails allready generates you a migration with

    def self.up
      create_table :profiles do |t|
        t.string :name
        t.attached :next
    
        t.timestamps
      end
    end
    

    however you can override the default migration template by placing it in /lib/templates/active_record/model/migration.rb

    You should write a rake my_gem:setup task to put the file there I haven't tried, but i guess rails does not search in non-engine gems for these templates

    Your migration template contents would then look like

    class <%= migration_class_name %> < ActiveRecord::Migration
      def self.up
        create_table :<%= table_name %> do |t|
    <% for attribute in attributes -%>
      <% if attribute.type.to_s == "attached" %>
          t.string :<%= attribute.name %>_identifier
          t.string :<%= attribute.name %>_extension
          t.integer :<%= attribute.name %>_size
      <% else %>
          t.<%= attribute.type %> :<%= attribute.name %>
      <% end %>
    <% end -%>
    <% if options[:timestamps] %>
          t.timestamps
    <% end -%>
        end
      end
    
      def self.down
        drop_table :<%= table_name %>
      end
    end
    

提交回复
热议问题