如何在 Ruby 中有条件地委托活动记录

Thu*_*ppy 3 ruby activerecord delegates ruby-on-rails-3

是否可以根据条件逻辑将一个函数或一系列函数委托给多个其他对象之一?

前任:

class Item
    has_one :thing
    has_one :other_thing

    delegate :foo,
             :bar
             to: :[thing or other_thing]
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我希望将 foo 和 bar 操作委托给该事物,或者基于某些条件逻辑委托给其他事物。

可能相关:带有委托和条件的 Active Record

Thu*_*ppy 5

是的。

除了其他对象之外,函数还可以委托给其他函数。

前任:

class Item
  has_one :thing
  has_one :other_thing

  delegate :foo,
           :bar
           to: :correct_thing

  def correct_thing
    [conditional] ? thing : other_thing
  end
end
Run Code Online (Sandbox Code Playgroud)