有没有办法将 Rails ActiveRecord 属性设为私有? [英] Is there a way to make Rails ActiveRecord attributes private?
问题描述
默认情况下,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.
那么,有没有办法让一些属性从字面上private
?
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 instead (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屋!