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

Leo*_*sov 32 activerecord private ruby-on-rails

默认情况下,ActiveRecord从相应的数据库表中获取所有字段,并为所有字段创建公共属性.

我认为公开模型中的所有属性是合理的.更重要的是,暴露出用于内部使用的属性会使模型的界面混乱,并违反封装原则.

那么,有没有办法从字面上制作一些属性private

或者,也许我应该转向其他ORM?

Mat*_*ggs 32

Jordini大部分都在那里

大多数active_record都发生在method_missing中.如果您预先定义方法,它将不会触及该方法的method_missing,并使用您的方法(有效覆盖,但不是真的)

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
Run Code Online (Sandbox Code Playgroud)

  • @TC:因为那些实际上不会正确跟踪属性.write_attribute/read_attribute方法是与active_record接口的方式 (2认同)
  • @Overflow012你也可以做`your_model_instance.send(:my_private_attribute =,"foo")`.Ruby采用(理智)方法,即隐私目标是其他程序员意图的指示,而不是永远不会被打破的锁. (2认同)
  • `def my_private_attribute; 超级`将会做 - 不需要重新定义它,然后当然使它像上面那样私有或以我喜欢的方式`private:my_private_attribute` (2认同)

jor*_*inl 5

好吧,你总是可以覆盖这些方法......

class YourModel < ActiveRecord::Base

  private

  def my_private_attribute
    self[:my_private_attribute]
  end

  def my_private_attribute=(val)
    self[:my_private_attribute] = val
  end

end
Run Code Online (Sandbox Code Playgroud)


小智 5

最近偶然发现了这一点.如果你想私人写作和阅读以及这样的公共阅读

class YourModel < ActiveRecord::Base

  attr_reader :attribute

  private

  attr_accessor :attribute


end
Run Code Online (Sandbox Code Playgroud)

似乎对我来说很好.您可以使用attr_reader,attr_writer和attr_accessor来决定应该公开什么以及什么应该是私有的.