2015-07-21 72 views
0

我有一個從另一個模型依賴模型的新實例的時候,我已經在我的routes.rb文件NoMethodError Rails中創建模型

Rails.application.routes.draw do 
    resources :events do 
    resources :guests 
    get :whereabouts 
    end 
    devise_for :users, :controllers => { registrations: 'registrations' } 

models/event.rb指定它像這樣:

class Guest < ActiveRecord::Base 
    belongs_to :event 
end 

當我訪問http://localhost:3000/events/2/guests/它工作正常,但是當我訪問http://localhost:3000/events/2/guests/new我得到

undefined method `guests_path' for #<#<Class:0x00000004074f78>:0x0000000aaf67c0> 

從我views/guests/_form.html.erb文件的行#1這是

<%= 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 %> 

我改變了路徑的正確的人,因爲現在guests_path應該event_guests_path,但我不知道我的表單在哪裏更改以使其正常工作。

任何線索?我的路由是否錯誤?

回答

1

你的路由正確。但來賓對象從事件一個依賴,所以你不得不形式更改爲:

<%= form_for [@event, @guest] do |f| %> 
... 
<% end %> 

必須在控制器,你可能不喜歡的東西初始化了@event變量:

@event = Event.find(params[:event_id]) 
@guest = @event.guests.build 
0

the docs

對於命名空間的路線,像admin_post_url

<%= form_for([:admin, @post]) do |f| %> 
    ... 
<% end %> 

所以,你的情況,你可能想這一點:

<%= form_for([:event, @guest]) do |f| %>