Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - using `rails generate model` to specify non-nullable field type

According to the rails documentation

http://guides.rubyonrails.org/migrations.html

2.3 Supported Type Modifiers says it should be possible to modify fields to allow or disallow NULL in the column, and that it's possible to do this on the terminal

This is what I want to appear in the migration file

class CreateTestModels < ActiveRecord::Migration
  def change
    create_table :test_models do |t|
      t.string:non_nullable, :null => false

      t.timestamps
    end
  end
end

On the terminal, I've tried

rails generate model TestModel non_nullable:string{null}
rails generate model TestModel 'non_nullable:string{null: false}'

I can't think of any other way to express it

Note: I already know you can go into the migration file and manually add it. That's not what I'm looking for.

like image 801
Alan Avatar asked Jan 20 '14 01:01

Alan


1 Answers

The docs mention that

Some commonly used type modifiers can be passed directly on the command line. They are enclosed by curly braces and follow the field type

but they don't give details about which "commonly used" modifiers willl work.

As pointed out by mr rogers there are only three supported options:

  • length for string/text/binary/integer (name:string{255})
  • precision,scale for decimal (dollar_fragment:decimal{3,2})
  • polymorphic for references/belongs_to (agent:references{polymorphic})

As mentioned by user2903934 it may be possible to make this work from the command line as a hack.

NOTE: this is a hack. i wouldn't recommend doing this but it does answer your question.

rails generate model TestModel 'non_nullable, null => false:string'

It looks like it splits on the first colon, so we can use a hashrocket syntax to sneak options in there. This yields:

class CreateTestModels < ActiveRecord::Migration
  def change
    create_table :test_models do |t|
      t.string :non_nullable, null => false

      t.timestamps
    end
  end
end

That obviously isn't officially supported, it just happens to work.

like image 141
devpuppy Avatar answered Oct 11 '22 09:10

devpuppy