当我使用attr_accessible来指定哪些字段从我型我会暴露,这是真的脚本/控制台呢?我的意思是什么,我没有指定为attr_accessible将无法访问,以及通过控制台?

有帮助吗?

解决方案

这是仅适用于质量分配真。举例来说,如果你要一套attr_protected :protected模型中的:

>> Person.new(:protected => "test")
=> #<Person protected: nil>

相反,你可以设置你想要的访问使用attr_accessible所有属性。

但是,以下将仍然工作:

>> person = Person.new
=> #<Person protected: nil>
>> person.protected = "test"
=> #<Person protected: "test">

这是相同的行为,如控制器,视图等attr_protected仅防止变量质量分配,主要是从表格等。

其他提示

在控制台究竟表现为Rails应用程序。如果您保护的特定模型的一些属性,你将不能够大规模分配这些从控制台或Rails应用程序本身或者属性。

我发现为什么:

指定可以经由质量分配设定模型的属性,如new(attributes)update_attributes(attributes),或attributes=(attributes)的白名单。 这是attr_protected宏的相反:

 Mass-assignment will only set attributes in this list, to assign to the rest of 
attributes you can use direct writer methods. This is meant to protect sensitive  
attributes from being overwritten by malicious users tampering with URLs or forms. 
If you‘d rather start from an all-open default and restrict attributes as needed,
have a look at `attr_protected`.

因此,这意味着,它只是避免质量分配,但我仍然可以设置的值。

当您指定出头是attr_accessible只有那些东西都可以在控制台或通过网站访问接口。

例如:假设你做出nameemailattr_accessible

attr_accessible :name, :email

和左出created_atupdated_at(其你应该)。 那么你只能编辑/控制台更新这些字段。

如果您希望公开场形成你的模型,你可以使用

attr_accessor :meth # for getter and setters
attr_writer :meth # for setters
attr_reader :meth # for getters

或者,如果你想添加一些行为,你的属性,你就必须使用虚拟属性

def meth=(args)
 ...
end
def meth
 ...
end

欢呼声。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top