简体   繁体   English

在Rails中初始化class_attribute的正确方法是什么?

[英]What's the proper way to initialize a class_attribute in Rails?

What's the proper way to initialize a class_attribute in Rails? 在Rails中初始化class_attribute的正确方法是什么?

I am using this: 我用这个:

class Foo < ActiveRecord::Base

  class_attribute :foobar
  self.foobar = []

  # ...

end

Which seems to work fine, but also seems to look a bit non-Railsy to me. 这似乎工作正常,但似乎对我来说看起来有点非Railsy。

Everything is described here: http://apidock.com/rails/Class/class_attribute 这里描述了一切: http//apidock.com/rails/Class/class_attribute

If you click on "Show source" you will see there are no options available to set default value. 如果单击“显示源”,您将看到没有可用于设置默认值的选项。 You are doing it right. 你做得对。

A default option was added on branch master of Rails this year, check: https://github.com/rails/rails/pull/29270 . 今年在Rails的分支主机上添加了一个default选项,请查看: https//github.com/rails/rails/pull/29270 With this change, you can do: 通过此更改,您可以执行以下操作:

class Foo < ActiveRecord::Base
  class_attribute :foobar, default: []
end

What you've done works well (unless you are inheriting). 你做得很好(除非你继承)。

If you are inheriting from this class you can use the inherited method to avoid 'leaking'. 如果您继承自此类,则可以使用inherited方法来避免“泄漏”。

def self.inherited(sub_class)
  self.foobar = self.foobar.clone
  # or `self.foobar = []`
end

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

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