开发者

How can I overwrite attr_readonly?

I have an attribute that is protected using attr_readonly to prevent users from altering the field.

I want to be able to alter it using an instance method. Is thi开发者_开发技巧s possible?


You should use attr_protected here instead of attr_readonly. Then you will be protected from mass-asignment from forms.

#in model
attr_protected :my_field
#in controller
obj = MyModel.new({:my_field => "dsadsad"})
obj.my_field
#=> nil
obj.my_field = "ololo"
obj.my_field
#=> "ololo"

EDIT

Situation: you need to set email only once: while creating user. Then you want to edit email only if you're admin.

# Model
attr_protected :email

# Controller
def create
  @user = User.new params[:user]
  @user.email = params[:user][:email]
  @user.save
  respond_with @user
end

def update
  @user = User.find params[:id]
  @user.email = params[:user][:email] if curent_user.admin?
  @user.update_attributes params[:user]
  respond_with @user
end

Also check out: http://railscasts.com/episodes/237-dynamic-attr-accessible

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜