attr_accessible
将所有未指定的属性标记为受保护,但我需要在创建时仍写入一些关键属性,如attr_readonly
.
我的模型设置如下:
class Foo < ActiveRecord::Base
attr_accessible :bar, :baz
attr_readonly :shiz
end
class FooParent < ActiveRecord::Base
has_many :foos
end
@foo_parent.foos.build(:bar => 1, :baz => 2, :shiz => 3) # Can't mass-assign protected attribute: :shiz
这里明显的解决方法是不使用attr_readonly
,创建没有关键属性的对象,然后设置并保存它们。这种方法的缺点是我现在至少有 2 次写入,而且这种创建方法需要尽可能地提高性能。
@foo_parent.foos.build(:bar => 1, :baz => 2) # write #1
@foo_parent.foos.each do |f|
f.update_attribute(:baz, 3) # write #2 and more
end
如何在 1 次写入中创建具有可访问属性和只读属性的对象而不触发Can't mass-assign protected attributes
错误,同时在创建后仍然享受只读保护的好处?