我正在使用 Ruby on Rails v3.2.2,我想知道它是否是声明 Active Record Association 的有效方法。在混合模块中。 为什么?
更多:
- 这种方法的优点和缺点是什么?
- 有什么需要注意的地方吗?
- 有处方吗?
注意:我想 DRY(不要重复自己)我的代码,因为与我的 Active Record 关联相关的语句对于多个模型是相同的。
最佳答案
继续做吧!关于您的问题:
关于 1:最大的优势是您拥有干净的代码库,没有重复的代码;我能想到的最大缺点是,对于查看您的代码的人来说,它可能不会立即显而易见。
关于 3:您必须在
included
回调中或使用新的ActiveSupport::Concern
扩展来定义关联。
例子:
# using the standard include callback
module LocationAwareness
def self.included(base)
base.has_one :location
end
end
或
# using ActiveSupport::Concern
module LocationAwareness
extend ActiveSupport::Concern
included do
base.has_one :location
end
end
然后你可以像这样在你的模型中使用它:
class Person < ActiveRecord::Base
include LocationAwareness
end
class Gig < ActiveRecord::Base
include LocationAwareness
end
#...
如果您有更多的共享行为而不仅仅是“只是”关联,那么这种方法当然开始变得更有意义......
关于ruby-on-rails - 是在 mixin 模块中声明 Active Record Associations 的有效方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12709492/