Error de nombre de constante no inicializado de Ruby

I have this strange error I don't understand. I have a model User definido como:

class User < ActiveRecord::Base
validates_presence_of :name, :email

has_many :caves
end

And an associated model Cave definido como:

class Cave < ActiveRecord::Base
  belongs_to :user
end

On my user's show method, I offer to create a new cave:

<%= form_for([@user, @user.caves.build]) do |f| %>
<div class="field">
  <%= f.label :name %><br />
  <%= f.text_field :name %>
</div>
<div class="actions">
  <%= f.submit %>
</div>

But when I display the page, I get the following error:

NameError in Users#show
Showing E:/Vinisync/app/views/users/show.html.erb where line #19 raised:

uninitialized constant User::Cafe

Extracted source (around line #19):
16: </p>
17: 
18: <h2>Add a Cave</h2>
19: <%= form_for([@user, @user.caves.build]) do |f| %>
20:   <div class="field">
21:     <%= f.label :name %><br />
22:     <%= f.text_field :name %>

I don't know where the hell this 'Cafe' comes from, I don't have this word anywhere in my code!
What I've noticed is that if I rename the associated in User.rb has has_many :cave en lugar de has_many :caves as currently (and change it in the form in the users's show.html.erb, the page displays normally. But my relationshiop is one to many, so it should read as 'caves' in User, not 'cave'. I believe I've read all related questions here on SO and elsewhere, but I none of the solutions seem to apply.

preguntado el 10 de marzo de 12 a las 15:03

3 Respuestas

Sounds like Rails doesn't realize that the singular of Caves is Cave. You can set this up manually in config/initializers/inflections.rb:

inflect.irregular 'cave', 'caves'

Then it will try to find Cave instead of Cafe.

respondido 10 mar '12, 16:03

Thanks, that does it! You can't know how much I am relieved to have gotten rid of this, it's been driving me crazy fo days! Is that frequent to have this kind of errors? - Antoine

Usually Rails is pretty good about inflections and finding the correct pluralized or singularized word... Words with "v" in them seem to mess it up more often than usual though. For example, the default singular of "loves" is "lofe." - Verático

Exactly the same error as I had then. I'm new to ruby, I'll keep an eye on this then, especially since I intend my models to be partly in french. - Antoine

Your problem is that Ruby uses the somewhat "inventive" deflector to singularize your "Caves" and ends up generating "Cafe".

You can fix the behavior in inflections.rb in your config.

respondido 10 mar '12, 16:03

The error points you to your show.html.erb view file, not to your new.html.erb ver archivo.

maybe you have a typo on the show.html.erb. ¡Revisalo!

respondido 10 mar '12, 16:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.