Question

I have this strange error I don't understand. I have a model User defined as:

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

has_many :caves
end

And an associated model Cave defined as:

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 instead of 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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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

maybe you have a typo on the show.html.erb. Check it!

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