Ruby on rails 用于测试关系计数的Rails def

Ruby on rails 用于测试关系计数的Rails def,ruby-on-rails,Ruby On Rails,我有一个位置模型。它包括: has_many :woassets has_many :workorders has_many :contacts has_many :worequests has_many :costprojects has_many :storerooms has_many :employees has_many :jobplans has_many :woschedules 在视图中,如果位置有任何关联的记录,我不希望使用delete按钮。因此,我正在这样做: <%

我有一个位置模型。它包括:

has_many :woassets
has_many :workorders
has_many :contacts
has_many :worequests
has_many :costprojects
has_many :storerooms
has_many :employees
has_many :jobplans
has_many :woschedules
在视图中,如果位置有任何关联的记录,我不希望使用
delete
按钮。因此,我正在这样做:

<% if location.workorders.count == 0 and location.woassets.count == 0 and location.contacts.count == 0 ...   %>

是否有更好的方法将
def
放入模型并在视图中使用

谢谢你的帮助

class Location 
  def has_assoc?
    [:rel1, :rel2, ...].any? { |r| send(r).present? }
  end
end
或者查看所有关联,而不仅仅是特定列表:

def has_assoc?
  Location.reflections.keys.any? { |r| send(r).present? }
end
他认为:

<% if location.has_assoc? %>


谢谢你的回答!!将类更改为位置