从Rails控制台创建数据

时间:2014-06-11 16:18:37

标签: ruby-on-rails

我想在db。中的模型上使用控制台创建数据。

这是模型:

class CreateBancas < ActiveRecord::Migration
  def change
    create_table :bancas do |t|
      t.string :nome
      t.string :cognome
      t.integer :numero
      t.integer :scadenza
      t.integer :type

      t.timestamps
    end
  end
end

当我做这样的查询时:

Banca.create!(:nome => "eric", :cognome => "noumedem", :scadenza => "2016", :numero => "123", :type => "1")
我有一些错误:

ActiveRecord::SubclassNotFound: Invalid single-table inheritance type: 1 is not a subclass of Banca
    from /home/eric/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.2/lib/active_record/inheritance.rb:178:in `subclass_from_attrs'
    from /home/eric/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.2/lib/active_record/inheritance.rb:22:in `new'
    from /home/eric/.rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.2/lib/active_record/validations.rb:39:in `create!'
    from (irb):307
    from /home/eric/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.2/lib/rails/commands/console.rb:90:in `start'
    from /home/eric/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.2/lib/rails/commands/console.rb:9:in `start'
    from /home/eric/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.0.2/lib/rails/commands.rb:62:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

:type列名更改为其他名称,例如。 :kind:role:banca_type

以下是代码:

rails g migration renameTypeColumnInBancasToKind

#db/migrate/renameTypeColumnInBancasToKind.rb

class CreateBancas < ActiveRecord::Migration
   def up
     rename_column :bancas, :type, :kind
   end

   def down
     rename_column :bancas, :kind, type
   end
end

以下是发生这种情况的原因:

在Rails中:type列的名称保留给STI (Single Table Inheritance) - 如果要填充:type列的值为&#34; 1&#34;,rails会自动尝试创建模型哪个class_name与此列的值完全相同。

所以,当你写:

Banca.create!(:type => "1")

这意味着:

1.create!

您没有名为&#34; 1&#34;的类,因此存在此错误的来源。在类中使用type属性的最佳做法是为其创建一个get方法和一个put方法。

#app/models/banca.rb
def type
  kind
end

def type=(value)
  kind = value
end

希望它会有所帮助,如果是的话投票:)