【问题标题】:Using record delegations with Mongoid Rails and Ruby在 Mongoid Rails 和 Ruby 中使用记录委托
【发布时间】:2014-02-25 12:38:31
【问题描述】:

我正在使用 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"

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

【问题讨论】:

    标签: ruby-on-rails ruby mongoid delegation


    【解决方案1】:

    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
    

    因此,您也可以将它用于您的模型。只要记住添加allow_nil: true,这样它就不会在没有功能时抛出异常。

    class Product
      embeds_one :feature
    
      delegate :color, to: :feature, allow_nil: true
    end
    

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 2011-07-21
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-04-25
      • 2014-08-09
      • 1970-01-01
      • 2020-10-02
      相关资源
      最近更新 更多