Ruby on rails 可在rails活动记录中访问属性

Ruby on rails 可在rails活动记录中访问属性,ruby-on-rails,ruby,activerecord,attr-accessible,Ruby On Rails,Ruby,Activerecord,Attr Accessible,当我使用attr\u accessible来指定我将公开模型中的哪些字段时,脚本/控制台也是这样吗?我的意思是,我没有指定为“属性可访问”的东西也不能通过控制台访问?我找到了原因: 指定可通过批量分配设置的模型属性白名单,例如新建(属性),更新属性(属性),或属性=(属性)。 这与受attr_保护的宏相反: Mass-assignment will only set attributes in this list, to assign to the rest of attributes yo

当我使用
attr\u accessible
来指定我将公开模型中的哪些字段时,脚本/控制台也是这样吗?我的意思是,我没有指定为“属性可访问”的东西也不能通过控制台访问?

我找到了原因:

指定可通过批量分配设置的模型属性白名单,例如
新建(属性)
更新属性(属性)
,或
属性=(属性)
。 这与受attr_保护的宏相反:

 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`.

这意味着它只是避免了大规模赋值,但我仍然可以设置一个值。

控制台的行为与Rails应用程序完全相同。如果您保护了特定型号的某些属性,则无法从控制台或Rails应用程序本身批量分配这些属性。

这仅适用于批量分配。例如,如果要在模型中设置
attr\u protected:protected

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

这与控制器、视图等中的行为相同。
attr\u protected
仅防止大量变量赋值,主要是表单等。

当您指定某些东西可
attr\u访问时
只有这些东西可以在控制台或通过网站界面访问

例如:假设您将
名称
电子邮件
设置为可访问
属性

attr_accessible :name, :email
在处创建的
和在
处更新的
中省略(您应该这样做)。

然后,您只能在console中编辑/更新这些字段。

如果要从模型中公开字段,可以使用

attr_accessor :meth # for getter and setters
attr_writer :meth # for setters
attr_reader :meth # for getters
或者,如果您想在属性中添加一些行为,则必须使用虚拟属性

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

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