Reputation: 177
I have a model that depends from another model, I have specified it like this in my routes.rb
file
Rails.application.routes.draw do
resources :events do
resources :guests
get :whereabouts
end
devise_for :users, :controllers => { registrations: 'registrations' }
models/event.rb
:
class Event < ActiveRecord::Base
belongs_to :user
has_many :guests
end
models/guest.rb
:
class Guest < ActiveRecord::Base
belongs_to :event
end
When I access http://localhost:3000/events/2/guests/
it works properly but when I access http://localhost:3000/events/2/guests/new
I get
undefined method `guests_path' for #<#<Class:0x00000004074f78>:0x0000000aaf67c0>
from line #1 of my views/guests/_form.html.erb
file which is
<%= form_for(@guest) do |f| %>
<% if @guest.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@guest.errors.count, "error") %> prohibited this event from being saved:</h2>
<ul>
<% @guest.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.text_field :first_name %>
</div>
<div class="field">
<%= f.text_field :last_name %>
</div>
<div class="field">
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I changed the paths to the proper ones since now guests_path
should be event_guests_path
, but I don't know where to change it in my form for it to work properly.
Any clue? Is my routing wrong?
Upvotes: 0
Views: 199
Reputation: 5528
Your routing is correct. But the guest object depends from the event one so you have to change the form to:
<%= form_for [@event, @guest] do |f| %>
...
<% end %>
you must have initialized the @event variable in the controller where you probably did something like:
@event = Event.find(params[:event_id])
@guest = @event.guests.build
Upvotes: 1
Reputation: 106017
From the docs:
For namespaced routes, like
admin_post_url
:<%= form_for([:admin, @post]) do |f| %> ... <% end %>
So, in your case, you probably want this:
<%= form_for([:event, @guest]) do |f| %>
Upvotes: 0