使属性仅在创建期间可批量分配 [英] Make attributes mass assignable only during creation
本文介绍了使属性仅在创建期间可批量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在创建模型对象的过程中,是否可以有一个只能批量赋值的属性?
Is it possible to have an attribute that is only mass-assignable during the creation of a model object?
例如,username
属性在创建对象时应该是可批量分配的,但之后不能(它应该是只读的).
For example, the username
attribute should be mass-assignable when creating the object, but not after that (it should be read-only).
推荐答案
这就是 attr_readonly
所做的:
class User < ActiveRecord::Base
attr_readonly :username
end
u = User.create(:username => 'dude')
u.username # => 'dude'
u.update_attributes(:username => 'dudette')
u.reload.username # => 'dude'
这篇关于使属性仅在创建期间可批量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文