Rails(生成模型)正在创建一个单一化的表而不是复数 - 该模型也在寻找一个单一的表

时间:2016-08-22 05:15:05

标签: ruby-on-rails ruby

我使用了命令:

$ rails g model Equipment

和rails执行以下操作:

  invoke  active_record
  create    db/migrate/20160822040448_create_equipment.rb
  create    app/models/equipment.rb
  invoke    test_unit
  create      test/models/equipment_test.rb
  create      test/fixtures/equipment.yml

如您所见,迁移是单一的!所以我重命名了迁移文件和表名,如下所示:

class CreateEquipments < ActiveRecord::Migration
  def change
    create_table :equipments do |t|
      # ...
    end
  end
end

现在,在运行$ rake db:migrate启动Rail的控制台$ rails c之后,当我尝试启动设备时,它错误地说它无法找到该表:

>> Equipment.new
PG::UndefinedTable: ERROR:  relation "equipment" does not exist
LINE 5:                WHERE a.attrelid = '"equipment"'::regclass
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                FROM pg_attribute a LEFT JOIN pg_attrdef d
                  ON a.attrelid = d.adrelid AND a.attnum = d.adnum
               WHERE a.attrelid = '"equipment"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "equipment" does not exist
LINE 5:                WHERE a.attrelid = '"equipment"'::regclass
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
                FROM pg_attribute a LEFT JOIN pg_attrdef d
                  ON a.attrelid = d.adrelid AND a.attnum = d.adnum
               WHERE a.attrelid = '"equipment"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum

我可以通过在模型中添加以下行来修补它:

    class Equipment < ActiveRecord::Base
        self.table_name = 'equipments'
        # ...
    end

但是,虽然这解决了问题,但我想知道导致问题的原因是什么。

最后注意:我尝试在控制台上运行#pluralize方法,并且它不会在那里复数字符串'Equipment':

>> 'Equipment'.pluralize
=> "Equipment"
>> 'door'.pluralize
=> "doors"

1 个答案:

答案 0 :(得分:5)