有代表和条件的活动记录 [英] Active Record with Delegate and conditions
本文介绍了有代表和条件的活动记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以在Active Record模型中使用委托,并使用之类的条件:if
Is it possible to use delegate in your Active Record model and use conditions like :if
on it?
class User < ApplicationRecord
delegate :company, :to => :master, :if => :has_master?
belongs_to :master, :class_name => "User"
def has_master?
master.present?
end
end
推荐答案
否,你不能,但你可以通过:allow_nil =>
No, you can't, but you can pass the :allow_nil => true
option to return nil if the master is nil.
class User < ActiveRecord::Base
delegate :company, :to => :master, :allow_nil => true
# ...
end
user.master = nil
user.company
# => nil
user.master = <#User ...>
user.company
# => ...
否则,您需要使用委托宏编写自己的自定义方法来更复杂选项。
Otherwise, you need to write your own custom method instead using the delegate macro for more complex options.
class User < ActiveRecord::Base
# ...
def company
master.company if has_master?
end
end
这篇关于有代表和条件的活动记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文