Home When call controller_name.classify.constantize I got #<NoMethodError: undefined method `belongs_to' for Relatorio:Class>"
Reply: 0

When call controller_name.classify.constantize I got #<NoMethodError: undefined method `belongs_to' for Relatorio:Class>"

Wellington1993
1#
Wellington1993 Published in 2017-11-03 16:01:20Z

I have a model:

class Relatorio < ApplicationRecord
  belongs_to :something
end

and

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

And I have this "before action" on super abstract Controller: "set_model_name":

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

In the line "constantize" of "controller_name.classify.constantize" from the set_model_name I got this error:

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

But after change the model to to use "ActiveRecord::Base" instead of "ApplicationRecord" the problem did not occur anymore : class Relatorio < ActiveRecord::Base belongs_to :something end

The problem is the use of "ActiveRecord::Base" is not the default and not is recommended to prevent monkey patching of "ActiveRecord".

What is the way to do "constantize" in a string changing that to Model, in cases where the model inherited from ActiveRecord ?

Thanks.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.337614 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO