有没有办法让Rails的ActiveRecord的属性私有? [英] Is there a way to make Rails ActiveRecord attributes private?

查看:132
本文介绍了有没有办法让Rails的ActiveRecord的属性私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在默认情况下,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

这篇关于有没有办法让Rails的ActiveRecord的属性私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆