Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to have an attribute that is only mass-assignable during the creation of a model object?

For example, the username attribute should be mass-assignable when creating the object, but not after that (it should be read-only).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

This is what attr_readonly does:

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...