如何在Ruby中有条件地委托Active Records

时间:2017-02-03 17:15:57

标签: ruby ruby-on-rails-3 activerecord delegates

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

例如:

class Item
    has_one :thing
    has_one :other_thing

    delegate :foo,
             :bar
             to: :[thing or other_thing]
end

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

可能相关:Active Record with Delegate and conditions

2 个答案:

答案 0 :(得分:3)

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

例如:

class Item
  has_one :thing
  has_one :other_thing

  delegate :foo,
           :bar
           to: :correct_thing

  def correct_thing
    [conditional] ? thing : other_thing
  end
end

答案 1 :(得分:0)

如下所示:

class Item
  has_one :thing
  has_one :other_thing

  delegate :foo,
           :bar
           to: :thing if: thing_condition?

  delegate :foo,
           :bar
           to: :otherthing if: otherthing_condition?
end