2014-03-31 31 views
2

我有一個form_for,我希望在文本區域中輸入文本廣告提交按鈕被點擊時我的控制器上的創建操作被調用,但相反,它注意到,但留在相同的頁面和瀏覽器的網址從localhost:3000更改爲http://localhost:3000/?utf8=✓&authenticity_token=6qNPP4KXB0B1G1X%2BG4UIakH5nhso1BJRlRJVukjL0jI%3D&speech%5Bwording%5D=&commit=Save+Speech - 我不明白這個網址在做什麼?即使當我在控制器中刪除我的create方法時,我應該會收到一個錯誤消息,說明「SpeechsController無法找到動作創建」,但是我只是得到了那麼長的url?Form_for提交按鈕沒有路由來創建操作

控制器:

class SpeechsController < ApplicationController 

def create 
end 

end 

形式:

<form class="col-lg-12"> 
    <div class="input-group" style="width:340px;text-align:center;margin:0 auto;"> 
     <%= form_for :speech, url: speechs_path do |f| %> 
     <%= f.text_area :wording, :class => "form-control", :style => "height:250px;width:540px;margin:0 auto;" %><br></br> 
     <%= f.submit :class => "btn btn-primary btn-lg btn-block" %> 
    <% end %> 
    </form> 

路線:

esources :speechs, except: [:new, :edit, :update, :destroy] do 
    collection do 
    get 'create' 
    end 
end 
    root "welcome#home" 

回答

1

首先,你應該必須將collection do get 'create'添加到您的routes.rb因爲create是默認的Rails路由操作之一。

其次,如果create是HTTP POST請求,您應該而不是get指定它。這就是爲什麼你有這麼長的網址。

在控制器內部,在您的create動作中添加.create方法。例如:

def create 
    @speech = Speech.create(params[:speech]) 
end 

現在,在您的視圖的形式應該是這樣的:

<%= form_for Speech.new do |f| %> 
    <%= f.text_area :wording %> 
    <%= f.submit %> 
<% end %> 

祝你好運!

0

這應該是理想的方式

控制器

class SpeechsController < ApplicationController 

def new 
@speech = Speech.new 
end 

def create 
    #Your Create logic here 
end 

end 

查看通知的@speech這裏鑑於

#app/views/speeches/new.html.erb 
<form class="col-lg-12"> 
    <div > 
     <%= form_for @speech do |f| %> 
     <%= f.text_area :wording, :class => "form-control" %> 
     <%= f.submit %> 
    <% end %> 
    </form> 

路線

resources :speeches, only: [:new,:create] 
+0

它會工作,如果窗體在我的主頁? – user3131148