2012-07-27 62 views
0

大家好林在我的應用程序工作,我遇到這個錯誤NoMethodError在控制器#新

NoMethodError in GasStationsController#new 

undefined method `gas_stations' for #<Class:0x12cf77510> 
Rails.root: /Users/Users/Documents/myapps/app1 

Application Trace | Framework Trace | Full Trace 
app/controllers/gas_stations_controller.rb:4:in `new' 

我不明白,如果我的路線都OK。我把我的routes.rb和我GasStationsController

Estaciones::Application.routes.draw do 
    root :to => "static_pages#home" 
    match '/contact', :to=>'static_pages#contact' 
    match '/about', :to=>'static_pages#about' 
    devise_for :users 
    resources :users do 
     resources :gas_stations 
    end 
    .... 

user_gas_stations GET /users/:user_id/gas_stations(.:format)      gas_stations#index 
         POST /users/:user_id/gas_stations(.:format)      gas_stations#create 
new_user_gas_station GET /users/:user_id/gas_stations/new(.:format)     gas_stations#new 
edit_user_gas_station GET /users/:user_id/gas_stations/:id/edit(.:format)    gas_stations#edit 
    user_gas_station GET /users/:user_id/gas_stations/:id(.:format)     gas_stations#show 
         PUT /users/:user_id/gas_stations/:id(.:format)     gas_stations#update 
         DELETE /users/:user_id/gas_stations/:id(.:format)     gas_stations#destroy 

正如你看到的方法是存在的 「gas_stations」

我只有這個我控制器上

class GasStationsController < ApplicationController 
    def new 
     @user = User.find(params[:user_id]) 
     @gas_station = @user.gas_stations.build 
    end 
end 

用戶模型

class User < ActiveRecord::Base 
# Include default devise modules. Others available are: 
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
devise :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable, :validatable 

# Setup accessible (or protected) attributes for your model 
attr_accessible :name, :email, :password, :password_confirmation, :remember_me 
# attr_accessible :title, :body 
has_many :cars 
validates_presence_of :email 
end 
+0

仍然沒有我得到這個錯誤:未定義的方法'建設」爲無:NilClass – BlackSan 2012-07-27 20:27:25

+0

應該在哪裏'''gas_stations'''從何而來?你把它定義爲'''has_many'''關係嗎?否則,有NoSuchMethod – phoet 2012-07-27 20:41:39

+0

類GasStation BlackSan 2012-07-27 20:49:13

回答

0

正如錯誤所述,Rails不知道gas_stations是什麼,因爲它與用戶有關。您需要設置該協會:

class User ... 
    ... 
    has_many :gas_stations 
    ...