我怎么能覆盖attr_readonly? [英] How can I overwrite attr_readonly?

查看:151
本文介绍了我怎么能覆盖attr_readonly?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用attr_readonly为prevent用户更改现场保护的属性。

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 this possible?

推荐答案

您应该使用 attr_protected 而不是 attr_readonly 。然后,你将得到保护,免受大规模asignment从形式。

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"

修改

情况:需要设置电子邮件只有一次:在创建用户。然后,你只希望,如果你是管理员编辑电子邮件。

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

另外,请查阅: http://railscasts.com/episodes/237-dynamic- ATTR访问的

这篇关于我怎么能覆盖attr_readonly?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆