Rails Active Record 中的 attr_accessible
当我使用 attr_accessible 指定我将公开模型中的哪些字段时,脚本/控制台也是如此吗?我的意思是我没有指定为 attr_accessible
的东西也无法通过 console 访问?
When I use the attr_accessible
to specify which fields from my Model I will expose, is it true for script/console as well? I mean something that I didn't specify as attr_accessible
won't be accessible as well through console ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这仅适用于批量分配。例如,如果您要在模型中设置
attr_protected :protected
:相反,您可以使用
attr_accessible
将您想要的所有属性设置为可访问。但是,以下内容仍然有效:
这与控制器、视图等中的行为相同。
attr_protected
仅防止变量的大规模分配,主要来自表单等。This is only true for mass assignment. For instance, if you were to set
attr_protected :protected
in your model:Conversely, you could set all attributes you want as accessible using
attr_accessible
.However, the following will still work:
This is the same behaviour as in controllers, views, etc.
attr_protected
only protects against mass assignment of variables, primarily from forms, etc.控制台的行为与 Rails 应用程序完全相同。如果您保护特定模型的某些属性,则您将无法从控制台或 Rails 应用程序本身批量分配这些属性。
The console behaves exactly as your Rails application. If you protected some attributes for a specific model, you won't be able to mass assign these attributes either from console or from the Rails app itself.
我找到了原因:
指定可以通过批量分配设置的模型属性白名单,例如
new(attributes)
、update_attributes(attributes)
或属性=(属性)
。这与 attr_protected 宏相反:
所以这意味着它只是避免批量分配,但我仍然可以设置一个值。
I found why:
Specifies a white list of model attributes that can be set via mass-assignment, such as
new(attributes)
,update_attributes(attributes)
, orattributes=(attributes)
.This is the opposite of the attr_protected macro:
So it means that it just avoid mass-assignment but i can still set a value.
当您将某些内容指定为
attr_accessible
时,只有这些内容可以在控制台或网站界面中访问。例如:假设您将
name
和email
设置为attr_accessible
:并省略了
created_at
和updated_at< /code> (你应该这样做)。
然后您只能在控制台中编辑/更新这些字段。
When you specify somethings to be
attr_accessible
only those things can be accessed in console or by website Interface.eg: Suppose you made
name
andemail
to beattr_accessible
:and left out
created_at
andupdated_at
(which you are supposed to).Then you can only edit/update those fields in console.
如果你想从你的模型中公开一个字段,你可以使用
,或者如果你想向你的属性添加一些行为,你必须使用虚拟属性
。
If you want to expose a field form your model, you can use
or if you want add some behaviour to your attribute, you ll have to use virtual attributes
cheers.