How to prevent rails from changing the path when the edit action is rendered from update action -
as far i'm aware standard rails pattern editing , updating resource.
i have route edit action on /users/:id/edit
, both put , patch route update action on /users/:id
.
here controller actions:
def edit @user = user.find params[:id] end def update @user = user.find params[:id] if @user.update_attributes(user_params) redirect_to @user, success: "changes saved" else flash.now.alert = "unable change account details" render :edit end end
and i'm using default form_for in form partial:
<%= form_for @user |f| %>
which creating following form in html:
<form accept-charset="utf-8" action="/users/1" id="edit_user_1" method="post"> ... <input name="_method" type="hidden" value="patch">
when call update_attributes
succeeds user being redirected correctly, when call fails (due activerecord validations) render action displays edit view correctly, path in user's browser changes /users/1/edit
/users/1
.
from i've read appears expected behaviour of rails, seems confusing me thought core idea behind rest url referred canonical view of resource?
if redirect_to
edit action instead of render
url should be, lose error messages on form.
is there more sensible way persist url , error messages dumping errors session before using redirect_to? i'd avoid if can.
update:
the reason want url persist (as errors) because i'm using current_page? set active states in navigation. therefore 'edit' action in menu loses it's highlighting if form submitted errors.
the reason in /users/1
view rendered #update
, not #edit
.
by default resource path of #update
same #show
, different request method get
, put
. so, when #update
renders html response, it's same #show
.
i think result acceptable, no matter path in result expected. found, if using redirect
, @user
instance changed branch new 1 losing errors , previous fillings.
there workaround on path such using session pass instance variable, don't think worth effort. current result enough.
add
manipulating active states easy. don't current_page?
needs code. use controller_path
, action_name
instead.
if controller_path == 'users' && (action_name == 'edit' || 'update') # add active class end
Comments
Post a Comment