当调用controller_name.classify.constantize时,我得到#<nomethoderror:undefined =“”method =“”`belongs_to'=“”for =“”relatorio:class =“”>&#34;

时间:2017-11-03 16:01:21

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord belongs-to

我有一个模特:

class Relatorio < ApplicationRecord
  belongs_to :something
end

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

我有这个&#34;行动之前&#34;在超级抽象控制器上:&#34; set_model_name&#34;:

def set_model_name
  @model_name ||= controller_name.classify
  @model_class ||= controller_name.classify.constantize
end

在第&#34; constantize&#34; of&#34; controller_name.classify.constantize&#34;从set_model_name我得到了这个错误:

#<NoMethodError: undefined method `belongs_to' for Relatorio:Class>"

但是在将模型更改为使用&#34; ActiveRecord :: Base&#34;而不是&#34; ApplicationRecord&#34;这个问题不再发生了:   class Relatorio&lt;的ActiveRecord :: Base的     belongs_to:东西   端

问题是使用&#34; ActiveRecord :: Base&#34;不是默认值,不建议不要使用#34; ActiveRecord&#34;进行猴子修补。

做什么&#34; constantize&#34;在模型中,如果模型继承自ActiveRecord?

,则将其更改为Model

感谢。

0 个答案:

没有答案