有没有办法在Rails模型中说只有在创建新记录时才能访问该属性但是在更新时不可访问?
类似的东西:
class DesiredModel < ActiveRecord::Base
attr_accessible :type, :only => [:create] # this is just example
attr_accessible :type if :new_record? # this is just example
end
答案 0 :(得分:2)
attr_accessible
无法以这种方式参数化。但是,您可以使用:as => :create
添加类似条件的角色。通过这种方式,您可以通过向其添加角色来批量生成此字段的质量分配。
attr_accessible :type, :as => :create
...
model.assign_attributes(params[:model], :create)
答案 1 :(得分:2)
您可以使用attr_readonly。它允许您设置属性值,但在更新记录时忽略该属性。如果在更新后调用模型上的重新加载,您将看到该属性仍然相同。