簡體   English   中英

檢查控制器是否在Rails中有模型

[英]Check if controller has a model in Rails

在下拉列表中,我已經將所有控制器類及其所有操作動態地移動到另一個下拉列表中,這些操作用於某些操作。 有些控制器沒有任何模型,如'DashboardsController',沒有Dashboard模型。 它僅用於顯示儀表板。

所以,基本上我需要過濾掉沒有模型的控制器。 我需要一個方法來傳遞控制器類並返回true/false

def has_model?(controller_klass)
 # TODO
end 

如果將控制器的名稱作為字符串傳入,則可以嘗試這樣的操作。 此解決方案假設您的模型在rails 5之前使用ActiveRecord ,其中ApplicationRecord用於定義模型; 在這種情況下,只需使用ApplicationRecord切換ActiveRecord::Base 此外,如果您的模型是普通的舊紅寶石對象(PO​​RO),那么這對它們不起作用。

def has_model?(controller_klass)
  begin
    class_string = controller_klass.to_s.gsub('Controller', '').singularize
    class_instance = class_string.constantize.new
    return class_instance.class.ancestors.include? ActiveRecord::Base 
  rescue NameError => e
    return false
  end
end 

此方法不依賴於異常,並且使用輸入作為Class或String。 它適用於任何Rails版本:

def has_model?(controller_klass)
  all_models = ActiveRecord::Base.descendants.map(&:to_s)
  model_klass_string = controller_klass.to_s.sub(/Controller$/,'').singularize
  all_models.include?(model_klass_string)
end

注意:您需要設置

config.eager_load = true

配置/環境/ development.rb

如果您有非ActiveRecord模型,則可以忽略之前的注釋並使用:

all_models = Dir[File.join(Rails.root,"app/models", "**","*.rb")].map{|f| File.basename(f,'.rb').camelize}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM