Question

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
end

This is my Serie model:

class Serie < ActiveRecord::Base
  belongs_to :publisher
end

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
end

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?

Was it helpful?

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'
end

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.

OTHER TIPS

I believe John's answer is the best one.

You can also directly specify the class name in the has_many declaration

has_many :series, :class_name => 'Serie'

Your has_many relationship name is fine, but your model name is wrong.

As the singular and plural of series are both series, you need to rename your model from Serie to Series. After that, everything should be fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top