Ruby on Rails generates model field:type - what are the options for field:type?

后端 未结 8 1843
遥遥无期
遥遥无期 2020-12-22 15:42

I\'m trying to generate a new model and forget the syntax for referencing another model\'s ID. I\'d look it up myself, but I haven\'t figured out, among all my Ruby on Rails

8条回答
  •  别那么骄傲
    2020-12-22 16:24

    To create a model that references another, use the Ruby on Rails model generator:

    $ rails g model wheel car:references
    

    That produces app/models/wheel.rb:

    class Wheel < ActiveRecord::Base
      belongs_to :car
    end
    

    And adds the following migration:

    class CreateWheels < ActiveRecord::Migration
      def self.up
        create_table :wheels do |t|
          t.references :car
    
          t.timestamps
        end
      end
    
      def self.down
        drop_table :wheels
      end
    end
    

    When you run the migration, the following will end up in your db/schema.rb:

    $ rake db:migrate
    
    create_table "wheels", :force => true do |t|
      t.integer  "car_id"
      t.datetime "created_at"
      t.datetime "updated_at"
    end
    

    As for documentation, a starting point for rails generators is Ruby on Rails: A Guide to The Rails Command Line which points you to API Documentation for more about available field types.

提交回复
热议问题