2012-01-04 77 views
3

我有這張表添加稅款。Rails 3.更改表單提交時的重定向

|Name | Rate | Description | 
|IVA | 16 | something | 
|  |  |    | 
|  |  |    | 
|  |  |    | 
save 

所以,如果你點擊保存,將保存輸入的新項目。我有當我提交表單爲此在taxes_controller.rb

@account = Account.find(current_user.account_id) 
3.times {@account.taxes.build} 

那麼這個形式

<%= form_for(@account) do |f| %> 
<table style="width:400px;" class="taxes"> 
    <tr> 
    <th>Name</th> 
    <th>Rate</th> 
    <th>Description</th> 
    </tr> 

<%= f.fields_for :taxes do |builder| %> 
    <tr> 
    <td><%= builder.text_field :name %></td> 
    <td><%= builder.text_field :rate %> %</td> 
    <td><%= builder.text_field :identification %></td> 
    </tr> 
<% end %> 
... 

,該領域也得到保存在數據庫中。問題是它重定向到賬戶顯示頁面;我知道它必須這樣做,因爲form_for(@account)

所以問題是:如何指定提交後表單要重定向的位置。在這種情況下,我想將它重定向到currect頁面。

回答

6

這只是間接的,因爲form_for(@account)

當您發佈表單時,它會觸發accounts_controller的創建(或更新)操作。

因此,在這2個動作(創建和更新)這個控制器,你應該做一個redirect_to ...

你說你想重定向到當前頁面。什麼是當前頁面?


好了,你可以做的是添加到您的路線:

resources :accounts, :module => "taxes" 

和你的形式將成爲

form_for [:taxes, @account] ... do |f| 

你的控制器將是app/controllers/taxes/accounts_controller.rb

class Taxes::AccountsController < ::AccountsController 
    def edit 

    end 

    def update 
     ... 
     redirect_to taxes_url 
    end 
end 

所以你用這種方法必須改變你的形式。您可以將路徑([@account]或[:taxes,@account])作爲您的部分參數傳遞給您...

另一種解決方案,也許更簡單,只需在您的表單中添加redirect_to輸入即可。您只有在您使用表格繳納稅款時才設置。並在控制器中,unless params[:redirect_to].blank?; redirect_to params[:redirect_to] end ...

+0

是的,但我也使用帳戶控制器來創建新的帳戶。但在上面的表格中,我只用它來創建新的稅收。當前頁面是http:// localhost:3000/taxes – leonel 2012-01-04 21:28:59

+0

我更新了我的信息 – Robin 2012-01-04 21:47:14

+0

我認爲在accounts_controller中你的意思是class Taxes :: AccountsController ' – leonel 2012-01-04 22:13:42