attr_accessor 和 attr_accessible 的区别 [英] Difference between attr_accessor and attr_accessible

查看:53
本文介绍了attr_accessor 和 attr_accessible 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails 中,attr_accessorattr_accessible 有什么区别?根据我的理解,使用 attr_accessor 用于为该变量创建 getter 和 setter 方法,以便我们可以像 Object.variableObject.variable 一样访问变量= some_value.

In Rails, what is the difference between attr_accessor and attr_accessible? From my understanding, using attr_accessor is used to create getter and setter methods for that variable, so that we can access the variable like Object.variable or Object.variable = some_value.

我读到 attr_accessible 使外部世界可以访问该特定变量.谁能告诉我有什么区别

I read that attr_accessible makes that specific variable accessible to the outside world. Can someone please tell me whats the difference

推荐答案

attr_accessor 是一种 Ruby 方法,可以生成 getter 和 setter.attr_accessible 是一个 Rails 方法,它允许您将值传递给批量赋值:new(attrs)update_attributes(attrs).

attr_accessor is a Ruby method that makes a getter and a setter. attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or update_attributes(attrs).

这是一个批量作业:

Order.new({ :type => 'Corn', :quantity => 6 })

您可以想象该订单可能还有折扣代码,例如 :price_off.如果您不将 :price_off 标记为 attr_accessible,您就可以阻止恶意代码这样做:

You can imagine that the order might also have a discount code, say :price_off. If you don't tag :price_off as attr_accessible you stop malicious code from being able to do like so:

Order.new({ :type => 'Corn', :quantity => 6, :price_off => 30 })

即使您的表单没有用于 :price_off 的字段,如果它在您的模型中,则默认情况下它是可用的.这意味着精心制作的 POST 仍然可以设置它.使用 attr_accessible 白名单列出那些可以批量分配的东西.

Even if your form doesn't have a field for :price_off, if it's in your model it's available by default. This means a crafted POST could still set it. Using attr_accessible white lists those things that can be mass assigned.

这篇关于attr_accessor 和 attr_accessible 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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