我正在使用 ruby 2、rails 4 和 mongoid-rails gem
我有两个模型:
class Product
embeds_one :feature
end
class Feature
embedded_in :product
field :color, type: String
end
假设我有一个产品:
p = Product.new
我希望能够调用类似的东西:
p.color = "blue"
不必做:
p.feature.color = "blue"
调用属性也是如此:
p.color
=> "blue"
对比不太理想(和现状)
p.feature.color
=> "blue"
我知道对于事件记录,您可以使用委托(delegate),但我如何在 mongoid 中设置它,而不必用大量引用特征模型的方法填充我的模型?
最佳答案
delegate
方法不限于 Active record - 它带有 Active Support 并且可以用在任何类上以将任何方法委托(delegate)给任何内部对象:
require 'active_support/all'
class A
def initialize(a)
@a = a
end
delegate :+, to: :@a
end
A.new(2) + 4 #=> 6
因此您也可以将它用于您的模型。请记住添加 allow_nil: true
,这样它就不会在没有功能时抛出异常。
class Product
embeds_one :feature
delegate :color, to: :feature, allow_nil: true
end
关于ruby-on-rails - 将记录委托(delegate)与 Mongoid Rails 和 Ruby 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21503432/