R – Getting a NameError with ActiveRecord and relationships


I've run into a problem when using a one to many relationship. I want to have each Series have one Publisher and that one Publisher has many Series.

This is my Publisher model:

class Publisher < ActiveRecord::Base
  validates_presence_of :name
  has_many :series

This is my Serie model:

class Serie < ActiveRecord::Base
  belongs_to :publisher

This is the failing test:

test "a publisher should have a list of series" do
  @publisher = Publisher.new :name => "Standaard Uitgeverij"
  @series = [ Serie.new(:name => "De avonturen van Urbanus", :publisher => @publisher),
              Serie.new(:name => "Suske en Wiske", :publisher => @publisher) ]
  assert_equal @series, @publisher.series

The test fails on the last line with NameError: uninitialized constant Publisher::Series.

I tried to save the publisher and the series, but this did not work. I tried it with only one serie, but this gives the same error.

Since I'm just starting out with Rails and Ruby, I am at a loss here. What am I doing wrong?

Best Solution

To address your actual question as mentioned in your comment (how can I name my model "Series"?), you need to make the Rails' Inflector aware of this exception to its default pluralization rules.

Add the following to config/environment.rb:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.uncountable 'series'

This will let you name your model as Series. You can test that it's worked using script/console:

>> "series".pluralize    #=> "series"
>> "series".singularize  #=> "series"

—I have to say that I've just tried using The Pluralizer and it would appear that Rails has knowledge of how to handle the word series built-in. Try it for yourself.

Related Question