Использование модификаторов столбцов из командной строки в Rails Migrations - PullRequest
0 голосов
/ 20 января 2019

Я читаю Руководства по Rails по миграциям .В нем говорится следующее, и я цитирую:

Некоторые часто используемые модификаторы типов могут быть переданы непосредственно в командной строке.Они заключены в фигурные скобки и следуют за типом поля:

В нем приведен пример:

$ bin/rails generate migration AddDetailsToProducts
'price:decimal{5,2}' supplier:references{polymorphic}

Руководство по Rails также предоставляет список модификаторов столбцов (ограничения SQL):

limit 
Sets the maximum size of the string/text/binary/integer fields.

precision 
Defines the precision for the decimal fields, representing the total number of digits in the number.

scale 
Defines the scale for the decimal fields, representing the number of digits after the decimal point.

polymorphic 
Adds a type column for belongs_to associations.

null 
Allows or disallows NULL values in the column.

default 
Allows to set a default value on the column.

index 
Adds an index for the column.

Итак, теперь я хочу использовать пару таких модификаторов столбцов из командной строки, но она не генерирует ожидаемую миграцию:

rails generate resource Employee first_name:string{limit,40, null,false} last_name:string{limit,40,null,false} birth_date:date sex:boolean salary:integer supervisor_id:integer{index,true} branch_id:integer{null,false,index,true}

Результат:

class CreateEmployees < ActiveRecord::Migration[5.1]
  def change
    create_table :employees do |t|
      t.string{limit,40, :first_name
      t.string :null,false}
      t.stringlimit :last_name
      t.string40 :last_name
      t.stringnull :last_name
      t.stringfalse :last_name
      t.date :birth_date
      t.boolean :sex
      t.integer :salary
      t.integerindex :supervisor_id
      t.integertrue :supervisor_id
      t.integernull :branch_id
      t.integerfalse :branch_id
      t.integerindex :branch_id
      t.integertrue :branch_id

      t.timestamps
    end
  end
end

Что я делаю не так?

1 Ответ

0 голосов
/ 20 января 2019

Формат, который вы используете, не совсем корректен. Посмотрите на rails g model --help для объяснения того, как использовать модификаторы. Вот модифицированная версия того, что вы ищете, хотя она не обрабатывает все интересующие вас случаи:

rails generate resource Employee first_name:string{40} last_name:string{40} birth_date:date sex:boolean salary:integer supervisor_id:integer:index branch_id:integer:index

Это генерирует следующее:

class CreateEmployees < ActiveRecord::Migration
  def change
    create_table :employees do |t|
      t.string :first_name, limit: 40
      t.string :last_name, limit: 40
      t.date :birth_date
      t.boolean :sex
      t.integer :salary
      t.integer :supervisor_id
      t.integer :branch_id

      t.timestamps null: false
    end
    add_index :employees, :supervisor_id
    add_index :employees, :branch_id
  end
end

Вам нужно будет вручную добавить null: false к тем записям, где вы хотите.

Но, если Branch и Supervisor также являются объектами AR, вы можете сделать следующее:

rails generate resource Employee first_name:string{40} last_name:string{40} birth_date:date sex:boolean salary:integer supervisor:references branch:references

, который генерирует следующее:

class CreateEmployees < ActiveRecord::Migration
  def change
    create_table :employees do |t|
      t.string :first_name, limit: 40
      t.string :last_name, limit: 40
      t.date :birth_date
      t.boolean :sex
      t.integer :salary
      t.references :supervisor, index: true, foreign_key: true
      t.references :branch, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

, что может быть больше, чем вы ищете

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...