2012-02-18 67 views
1

這裏是我的控制器:軌形成101

class TalentController < ApplicationController 
    def index 
    end 

    def new 
    @talent = Talent.new 
    end 

    def create 
     @talent.update_attributes!(params) 
    end 
end 

,這裏是我的應用程序/視圖/天賦/ new.html.haml:

= "Create new talent" 

= form_for @talent, :url => {:action=>:create, :controller=>"talent"}, :method => :post do |f| 
    = f.label :First_Name 
    = f.text_field :first_name 
    = f.label :Last_Name 
    = f.text_field :last_name 
    = f.label :City 
    = f.text_field :city 
    = f.label :State 
    = f.text_field :state 
    = f.label :Zip_code 
    = f.text_field :zip_code 
    = f.submit "Create" 

當我點擊Create按鈕,我得到這個錯誤。

No route matches [POST] "/talent/new" 

這裏是我的耙路線:

    /      {:action=>"index", :controller=>"talent"} 
talent_index GET /talent(.:format)   {:action=>"index", :controller=>"talent"} 
      POST /talent(.:format)   {:action=>"create", :controller=>"talent"} 
    new_talent GET /talent/new(.:format)  {:action=>"new", :controller=>"talent"} 
edit_talent GET /talent/:id/edit(.:format) {:action=>"edit", :controller=>"talent"} 
     talent GET /talent/:id(.:format)  {:action=>"show", :controller=>"talent"} 
      PUT /talent/:id(.:format)  {:action=>"update", :controller=>"talent"} 
      DELETE /talent/:id(.:format)  {:action=>"destroy", :controller=>"talent"} 

什麼我錯過這裏?

+0

儘量不指定':url'和':method'的形式。只是'= form_for @ talent'。 – 2012-02-18 02:55:33

+0

另外,在你的'create'動作中,你會得到一個異常,因爲'@ talent'沒有被定義。 – 2012-02-18 02:56:55

回答

0

我不知道爲什麼表單試圖發佈到new。但是,對代碼進行了一些改進。首先沒有必要通過:url:methodform_for。您需要的唯一東西是:

= form_for @talent do |f| 

Rails自動處理剩下的部分。

控制器的create方法中的代碼不正確。當調用create時,這是一個新的請求,因此@talent將不確定。你必須先設置它。第二個錯誤是您正在使用update_attributes,它用於更新數據庫中的現有記錄。你想創建一個新的記錄,所以你必須使用create。另一種方法是簡單地創建一個Talent的新實例並在其上調用save

因此,它應該是這樣的:

def create 
    @talent = Talent.create(params[:talent]) 
end 

或者這樣:

def create 
    @talent = Talent.new(params[:talent]) 
    if @talent.save 
    # Saved successfully, do a redirect or something... 
    else 
    # Validation failed. Show form again so the user can fix his input. 
    render :action => 'new' 
    end 
end