简体   繁体   English

Rails 4中属性的私有/受保护访问者

[英]Private/protected accessors to attributes in Rails 4

Supose that I have the following class: 假设我有以下课程:

class Foo < ActiveRecord::Base
    belongs_to :bar
end

In rails console I can do this: 在Rails控制台中,我可以这样做:

foo = Foo.new
foo.bar_id = 3

But this can violates the encapsulation principle. 但这会违反封装原理。 I think that is better idea do: 我认为这是个更好的主意:

foo = Foo.new
foo.bar = Bar.find(3);

And bar_id should be private/protected. 并且bar_id应该是私有的/受保护的。 This has nothing to do with the mass assignment and strong parameters but it is an security issue too. 这与mass assignmentstrong parameters无关,但这也是一个安全问题。

Is there any way to set to private some attributes? 有什么方法可以将某些属性设为私有?

Is there a way to make Rails ActiveRecord attributes private? 有没有办法将Rails ActiveRecord属性设为私有?

class MyModel < ActiveRecord::Base

  private

  def my_private_attribute
    self[:my_private_attribute]
  end

  def my_private_attribute=(val)
    write_attribute :my_private_attribute, val
  end
end

I don't think just making the write accessor private or protected will reliably prevent change via update_attribute or mass assignment. 我不认为仅将写访问器设置为私有或受保护就可以可靠地防止通过update_attribute或批量分配进行更改。

While it's not actually "private" per se, but you could get the desired effect by setting the attribute read_only, eg 尽管它本身并不是真正的“私有”,但是您可以通过设置属性read_only来获得所需的效果,例如

attr_readonly :bar_id

and if you do need to update the value "private-ly," access it as @bar_id. 如果确实需要更新值“ private-ly”,则以@bar_id的身份对其进行访问。 Per the docs, "Attributes listed as readonly will be used to create a new record but update operations will ignore these fields." 根据文档,“列为只读的属性将用于创建新记录,但更新操作将忽略这些字段。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM