rails 3创建设置值以计费

时间:2012-03-10 04:21:36

标签: ruby-on-rails ruby-on-rails-3.1

因此,合并后,我的RoR 3项目不再正确“创建”。默认属性设置正确,但不是我传入的属性:

1.9.3-p125 :020 > f=Ifilter.create(:name => "test2", :regex => "()" )
SQL (101.5ms)  INSERT INTO "ifilters" ("created_at", "name", "regex", "updated_at") VALUES    (?, ?, ?, ?)  [["created_at", Sat, 10 Mar 2012 03:36:24 UTC +00:00], ["name", nil], ["regex", nil], ["updated_at", Sat, 10 Mar 2012 03:36:24 UTC +00:00]]

=> #<Ifilter id: 2, name: nil, regex: nil, created_at: "2012-03-10 03:36:24", updated_at: "2012-03-10 03:36:24"> 

但是,保存仍然有效:

1.9.3-p125 :021 > f=Ifilter.new
 => #<Ifilter id: nil, name: nil, regex: nil, created_at: nil, updated_at: nil> 
1.9.3-p125 :022 > f.name = "test"
 => "test" 
1.9.3-p125 :023 > f.regex = "()"
 => "()" 
1.9.3-p125 :024 > f.save
  SQL (4.8ms)  INSERT INTO "ifilters" ("created_at", "name", "regex", "updated_at") VALUES (?, ?, ?, ?)  [["created_at", Sat, 10 Mar 2012 04:13:10 UTC +00:00], ["name", "test"], ["regex", "()"], ["updated_at", Sat, 10 Mar 2012 04:13:10 UTC +00:00]]
 => true 

发生了什么事?

谢谢!

2 个答案:

答案 0 :(得分:0)

您的模型上似乎有attr_accessiblehttp://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible

如果您正在使用它,则不会通过#new#create#update_attributes(以及更多)来设置未明确列出的属性。

答案 1 :(得分:0)

这通常在您启用了属性白名单时发生。确保通过attr_accessible宏定义通过模型中的质量分配可设置的属性:

class Ifilter
   attr_accessible :name, :regex
   ...
end