使用Mongoid Rails和Ruby的记录委托

Dav*_*vey 3 ruby ruby-on-rails delegation mongoid

我使用ruby 2,rails 4和mongoid-rails gem

我有两个型号:

class Product
  embeds_one :feature
end

class Feature
  embedded_in :product

  field :color, type: String
end
Run Code Online (Sandbox Code Playgroud)

让我们说我有一个产品:

p = Product.new
Run Code Online (Sandbox Code Playgroud)

我想能够打电话给:

p.color = "blue"
Run Code Online (Sandbox Code Playgroud)

而不是必须做:

p.feature.color = "blue"
Run Code Online (Sandbox Code Playgroud)

调用属性也是如此:

p.color
=> "blue"
Run Code Online (Sandbox Code Playgroud)

与不太理想(和目前的情况)

p.feature.color
=> "blue"
Run Code Online (Sandbox Code Playgroud)

我知道有活动记录你可以使用委托,但是如何在mongoid中设置它而不必用大量引用特征模型的方法来填充我的模型?

Bro*_*tse 7

delegate 方法不仅限于Active记录 - 它附带Active Support,可以在任何类上使用,以将任何方法委托给任何内部对象:

require 'active_support/all'
class A
  def initialize(a)
    @a = a
  end
  delegate :+, to: :@a
end

A.new(2) + 4     #=> 6
Run Code Online (Sandbox Code Playgroud)

因此,您也可以将它用于您的模型.只需记住添加allow_nil: true,如果它没有任何功能,它不会抛出异常.

class Product
  embeds_one :feature

  delegate :color, to: :feature, allow_nil: true
end
Run Code Online (Sandbox Code Playgroud)