0

我正在尝试使用 Rails 控制台来创建模型的对象实例。

可以使用手动方法创建实例并将其保存到数据库,如下所示:

1.9.3p125 :003 > subject = Subject.new
 => #<Subject id: nil, name: nil, position: nil, visible: false, created_at: nil, updated_at: nil> 
1.9.3p125 :004 > subject.name = "First Name"
 => "First Name" 
1.9.3p125 :005 > subject.position = 1
 => 1 
1.9.3p125 :006 > subject.visible = 'true'
 => "true" 
1.9.3p125 :007 > subject.save
(0.2ms)  BEGIN
SQL (0.6ms)  INSERT INTO `subjects` (`created_at`, `name`, `position`, `updated_at`, `visible`) VALUES ('2012-06-21 13:28:35', 'First Name', 1, '2012-06-21 13:28:35', 1)
(20.4ms)  COMMIT
 => true 
1.9.3p125 :008 > subject.id
 => 1 
1.9.3p125 :009 > subject.new_record?
 => false 

我对 RoR 完全陌生,所以我不知道从哪里开始解决这个错误:

1.9.3p125 :010 > subject = Subject.create(:name => "Second name", :position => 2)
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: name, position from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activemodel-3.2.3/lib/active_model/mass_assignment_security.rb:230:in `sanitize_for_mass_assignment'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/attribute_assignment.rb:75:in `assign_attributes'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/base.rb:498:in `initialize'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/persistence.rb:44:in `new'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/activerecord-3.2.3/lib/active_record/persistence.rb:44:in `create'
from (irb):10
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
from /Users/Nick/.rvm/gems/ruby-1.9.3-p125/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>'

这是我的主题模型:

class Subject < ActiveRecord::Base
  attr_accessible :title, :body, :name, :position
end

谢谢!

到目前为止我尝试过的事情:

  1. 退出和重新进入轨道 c.
  2. 输入“重新加载!” 进入轨道 c
  3. 重新打开终端
4

2 回答 2

1

您需要添加

attr_accessible :name, :position

到您的Subject模型,以便您可以一步创建它。它是安全的东西。你可以在这里阅读:

http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible

高频,..

于 2012-06-21T13:47:24.810 回答
0

我遇到了同样的问题,解决方案是这样做

subject=Subject.create(name: 'Second name', position: 2)

这对我来说可以

于 2015-07-29T14:33:57.813 回答