views:

191

answers:

3

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?

+1  A: 
John Topley
The model name is Serie (singular) but the name I want to use in the Publisher model is series (plural).
Thijs Wouters
I understand that but the model name should be Series because that is the correct singular form of the word Series.
John Topley
Ah, correct. Thanks. It works now the way I want.
Thijs Wouters
+1  A: 

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'
Mike H
I was just about to post this answer. But it doesn't explain why my code is not accepted. According to me the code follows the conventions. I would rather not include the class_name there.
Thijs Wouters
+1  A: 

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.

tomafro