leonel
leonel

Reputation: 10224

Rails 3. Change redirection upon form submission

I have this table where you add taxes.

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

So if you hit save, it will save the new items entered. I had to do this in taxes_controller.rb

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

Then this in the form

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

When I submit the form, the fields do get saved in the database. The problem is that it redirects to the Account show page; and I understand it has to do that because of form_for(@account).

So the question is: how can I specify where I want the form to redirect after submission. In this case, I want to redirect it to the currect page.

Upvotes: 3

Views: 7354

Answers (1)

Robin
Robin

Reputation: 21884

It's only indirectly because of form_for(@account).

When you post your form, it hits the create (or update) action of the accounts_controller.

So it's in these 2 actions (create and update) of this controller that you should do a redirect_to ....

You say that you want to redirect to the current page. What is the current page exactly?


Ok, so what you can do is add this to your routes:

resources :accounts, :module => "taxes"

And your form would become

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

Your controller would be in app/controllers/taxes/accounts_controller.rb

class Taxes::AccountsController < ::AccountsController
    def edit

    end

    def update
        ...
        redirect_to taxes_url
    end
end

So you'd have to change your form with this method. You could pass the path ([@account] or [:taxes, @account]) as an argument of your partial...

Another solution, maybe simpler, would be to just have a redirect_to input in your form. You set it only when you use your form in taxes. And in the controller, unless params[:redirect_to].blank?; redirect_to params[:redirect_to] end...

Upvotes: 6

Related Questions