DonMB
DonMB

Reputation: 2718

Rails couldn't find a valid model for - but association exists

I have a polymorphic table in rails MetaFieldsData which also belongs to a table MetaFields

class MetaFieldsData < ApplicationRecord
  belongs_to :owner, polymorphic: true
  belongs_to :meta_field
end
class MetaField < ApplicationRecord
  belongs_to :organization
  has_many :meta_fields_data
end

One model which is connected to the polymorphic table is called orders:

class Order < ApplicationRecord
  belongs_to :organization
  ...
  has_many :meta_fields_data, as: :owner

  ...

owner is my association class (the same what is imageable from the official RoR guide) Now I see a strange behaviour when I want to create a record on a the Order model:

MetaFieldsData.create(owner: order, meta_field: some_meta_field)

It throws:

NameError Exception: Rails couldn't find a valid model for MetaFieldsDatum association.
Please provide the :class_name option on the association declaration. If :class_name is already provided, make sure it's an ActiveRecord::Base subclass.

What is weird is that there is no class MetaFieldsDatum (note the typo here, coming from Rails). I searched all my code and there is no typo in there, also not in the class name definition.

This makes it impossible for me to create an actual MetaFieldsData on this table as Rails seems to interpret the naming wrong. What could possibly be wrong here?

Upvotes: 6

Views: 6647

Answers (2)

Okomikeruko
Okomikeruko

Reputation: 1173

I had the same problem, but my solution was different.

I had a typo in my belongs_to model which invalidated the model.

I discovered it was an invalid model by trying to access it in the console. Because it was invalid, Rails didn't load it and subsequently couldn't find it.

The error disappeared when I corrected the typo.

Upvotes: 6

kkp
kkp

Reputation: 446

Datum is used as a plural form of data. Notice that you have has_many :meta_fields_data and if you would to change that into a singular it would also be has_one :meta_fields_data. This is called inflection and it is a way of detecting plural forms of words, you can read up on how rails does it here https://api.rubyonrails.org/classes/ActiveSupport/Inflector/Inflections.html

In general you can either simply obide to what the error tells you and use datum in relationship name (specify class_name if you do so), or define your own inflection

Upvotes: 1

Related Questions