有没有办法让Rails的ActiveRecord的属性私有?没有办法、属性、Rails、ActiveRecord

2023-09-09 21:59:09 作者:野蛮小可爱

在默认情况下,ActiveRecord的需要从相应的数据库表中的所有领域,并创建公共属性全部。

By default, ActiveRecord takes all fields from the corresponding database table and creates public attributes for all of them.

我认为这是合理的没有的制作模型中公开的所有属性。更有甚者,揭露了旨在供内部使用杂波模型的接口,并违反了封装的原则。属性

I think that it's reasonable not to make all attributes in a model public. Even more, exposing attributes that are meant for internal use clutters the model's interface and violates the encapsulation principle.

那么,有没有一种方法,使一些属性字面上私人

So, is there a way to make some of the attributes literally private?

或者,也许我应该转移到其他的ORM?

Or, maybe I should move on to some other ORM?

推荐答案

Jordini是最有路

Jordini was most of the way there

大多数active_record的发生在method_missing的。如果你前面定义的方法,也不会打的method_missing该方法,并使用你何不换一种活(有效覆盖,但不是真的)

Most of active_record happens in method_missing. If you define the method up front, it won't hit method_missing for that method, and use yours in stead (effectively overwriting, but not really)

class YourModel < 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