0

I have a weird error in Rails with a model association.

There is a table called "Book" and it has many "news" (table "New"). However, when I add the association in the model, I get the following error:

rails uninitialized constant Book::News (NameError)

Book model:

class Book < ApplicationRecord
  belongs_to :editor
  belongs_to :author, optional: false
  has_many :news, dependent: :destroy
end

New model:

class New < ApplicationRecord
  belongs_to :book
end

I wonder if the name "new" is a problem for naming conventions in rails?

Thanks for your help.

1 Answer 1

2

Yeah New a really bad naming choice. Mostly because its gramatically incorrect.

news noun,
plural in form but singular in construction, often attributive
- https://www.merriam-webster.com/dictionary/news

Both the singular and plural form of news is news. New is actually an adjective and your model names should always be nouns (or compound nouns) as they are representations of things in the buisness logic of your application. Rails actually correctly inflects this when looking up the constant which explains why you are getting uninitialized constant Book::News.

Just change the name of your class and file to the correct form (news.rb and News) and use a dictionary if you are unsure of the pluralization or spelling as it will save you a lot of greif in a convention driven framework like rails.

1
  • That was it, thanks for the explanation, I will be more careful with English grammar next time!
    – nico_lrx
    Jan 18, 2020 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.