我对 ROR 有疑问:
我想创建一个名为“category2”的模型,我使用了以下命令:
导轨 g 型号类别 2
然后,我将文件 *db/migrate/20120521113409_create_category2s.rb* 更改为:
类 CreateCategory2s < ActiveRecord::Migration
定义变化
create_table :category2s do |t| t.string :name t.integer :position t.timestamps end
add_column :events, :category2_id, :integer
add_index :events, :category2_id
结束结尾
然后,
bundle exec rake db:migrate
当我打开控制台并输入
b = Category2.new(:name => 'Ruby', :position => 1)
它返回一个错误:
irb(main):009:0> b = Category2.new(:name => 'Ruby', :position => 1)
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: name, position
from /usr/local/lib/ruby/gems/1.9.1/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
from /usr/local/lib/ruby/gems/1.9.1/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal'
from /usr/local/lib/ruby/gems/1.9.1/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize'
from /usr/local/lib/ruby/gems/1.9.1/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security.rb:230:in `sanitize_for_mass_assignment'
from /usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/attribute_assignment.rb:75:in `assign_attributes'
from /usr/local/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_record/base.rb:498:in `initialize'
from (irb):9:in `new'
from (irb):9
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
这是什么意思?
如果我不添加参数,我只需输入:
irb(main):008:0> a = Category2.new
=> #< Category2 id: nil, name: nil, position: nil, created_at: nil, updated_at: nil>
这看起来不错的样子!
但是为什么不能指定“名称”和“位置”?
谢谢!