Monroe Mann
Monroe Mann

Reputation: 625

How to have two different redirect_to actions on one method in rails?

quick question that I'm sure has a quick answer. Everything works, except when I update the checklist on the homepage dashboard, it redirect to the profile page, because it's using the update method (I think) on the profiles controller. Any thoughts on how to get it to simply reload the page when the checklist is updated, without altering the ?

Here is the form:

<div class="col-md-4 col-xs-12">
      <div class="card">
        <div class="card-body">
          <h3 class="card-title">Onboarding Checklist</h3>
            <div class="onboarding-checklist-container">
              <%= form_for @profile do |f| %>
                <% Checklist.all.each do |item| %>
                  <%= check_box_tag "profile[checklist_ids][]", item.id, @profile.checklists.include?(item) %>
                  <%= item.name %><br />
                <% end %>
                <%= f.submit "Update" %>
              <% end %>
            <div><!--end onboarding-checklist-container div-->
        </div><!--end col card-body div-->
      </div><!--end card div-->
    </div><!--end col div-->

And here is the update method of the profiles controller

def update
    @profile = current_user.profile
    @profile.update_attributes(profile_params)
    redirect_to current_profile_path
  end

I feel like maybe I could do an if statement, but I'm not advanced yet enough to know how to do it.

I'm also unclear where it shows that this IS using the 'update' action. Is it?

Thank you!

Upvotes: 0

Views: 404

Answers (2)

Nimish Gupta
Nimish Gupta

Reputation: 3175

You can make use of rails redirect_back helper

def update
  @profile = current_user.profile
  @profile.update_attributes(profile_params)
  redirect_back fallback_location: current_profile_path
end

redirect_back will redirect you to the action from which request was server i.e request.referer. We are using fallback_location here for the case in which request.referer was nil.

Hope this helps

Upvotes: 1

Furkan E Apaydın
Furkan E Apaydın

Reputation: 324

You can add an additional input to one of your forms, something like this:

<input type="hidden" name="dashboardredirect" value="1"/> 

And then in your controller, you check for the existence of this value to decide your redirect:

def update
    @profile = current_user.profile
    @profile.update_attributes(profile_params)

    # Redirect to profile page if no dashboard redirect given,
    #  Redirect to dashboard if it is given.
    redirect_to params[:dashboardredirect].nil? ? current_profile_path : dashboard_path
  end

Upvotes: 1

Related Questions