How to generate scaffold for data type with “extra description” in Rails 3?

China☆狼群 提交于 2019-11-29 01:11:05
scarver2

In Rails 3.1 and below, the syntax is

rails generate scaffold LineItem name:string price:decimal

and then manually add the decimal properties to the migration file

t.decimal :price, :precision => 8, :scale => 2

In Rails 3.2, one can specify the decimal properties

rails generate scaffold LineItem name price:decimal{8,2}

NOTE: If you are running ZSH, the syntax requires a hyphen instead of a comma.

rails generate scaffold LineItem name price:decimal{8-2}

ANOTHER NOTE: If you are using bash under Mac OS X 10.9 try a dot instead of the comma

rails generate scaffold LineItem name price:decimal{8.2}

Almost a year later. Rails 3.2.11. Regular bash shell. Rails scaffold creates mess with syntax field_name:decimal{p,s} regardless of railties official doc. The confusion lays in simple fact that curly braces are meta-characters in bash (as well as in other shells) and needs to be escaped. See logged issue 4602 in scaffold generator repo.

If you using bash then use dot instead of comma as workaround.
Correct scaffold syntax field_name:decimal{p.s}

A few years later, with Rails 4.2 and bash (Linux) the following generator command works without problems:

bin/rails generate scaffold LineItem name:string price:decimal{8.2}

This will correctly generate the following example migration:

class CreateLineItems < ActiveRecord::Migration
  def change
    create_table :line_items do |t|
      t.string :name
      t.decimal :price, precision: 8, scale: 2

      t.timestamps null: false
    end
  end
end

New approach:

Create the migration with just add_column, e.g. rails generate migration AddPriceToLineItem price:integer

Then edit the migration and change it to be how you want it, e.g.

add_column :line_items, :price, :decimal, :precision => 8, :scale => 2

Getting the command line exactly right to do this has proved to be a major exercise in frustration and wasted time for me in the past. I recommend you follow this procedure and move on.

Here's how I did it:

rails generate scaffold LineItem ... amount:decimal ...

The ... are any other fields we need in the scaffold, like date:date, item:string, category:references...

Then I modified the migration to look like:

create_table :line_items do |t|
  .
  .
  .
  t.decimal :amount, :precision => 8, :scale => 2

Then

rake db:migrate

This holds values between -999,999.99 to 999,999.99.

Here is some (marginally) useful reference: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html

This is the accurate and most simple way to do this under Rails 5.x:

rails generate scaffold LineItem name price:decimal{'8,2'}

Pay special attention to the single quotes used when specifying scale and precision.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!