首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > Ruby Rails >

Ruby on rails3 资料库新增有关问题

2012-09-23 
Ruby on rails3 资料库新增问题我建了一个Model:Python coderails g model category2然后将db/migrate/201

Ruby on rails3 资料库新增问题
我建了一个Model:

Python code
rails g model category2


然后将db/migrate/20120521113409_create_category2s.rb中的内容改变为如下:
Python code
class CreateCategory2s < ActiveRecord::Migration  def change    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  endend


产生资料表:
bundle exec rake db:migrate

接着打开console:
Python code
rails c


在输入
Python code
b = Category2.new( :name => 'Ruby', :position => 1 )
时出现了如下问题:

Python code
irb(main):008:0> a = Category2.new=> #<Category2 id: nil, name: nil, position: nil, created_at: nil, updated_at: nil>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>'


这是什么原因造成的?怎么改?

[解决办法]
在你项目的目录下,/app/models/category2.rb 文件中,看下name和position两个变量是不是attr_accessible。
[解决办法]
在model中加入 attr_accessible :name, :position

热点排行