渲染模板并在浏览器中更改 url 字符串? [英] Render template and change url string in browser?

查看:20
本文介绍了渲染模板并在浏览器中更改 url 字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个操作 - 编辑和更新.编辑中的表单将值提交给更新操作.当保存模型失败时,我会渲染编辑 teplate,其中用户会看到错误,并且字段预先填充了他之前填写的内容.有一个巨大的但对我来说 - 在用户浏览器的 URL 面板中有/user/update,即使(并且因为)我呈现编辑模板.我可以通过在更新操作中将一些参数传递给渲染方法以某种方式改变它吗?我不希望用户看到除了编辑之外还有任何(更新)操作.可能吗?

解决方案

有两种方法可以解决这个问题:

1) 从更新操作重定向回编辑操作,而不是仅仅渲染模板,并传递您想用来填充正在编辑的对象的错误消息和属性.这将导致 URL 为/user/edit.

<前>定义更新@user = User.find(params[:id])如果@user.update_attributes params[:user]...别的redirect_to edit_user_path(@user, :messages => @user.errors)结尾结尾

2) 发布到编辑操作而不是更新操作并完全删除更新操作.你可以用request.post吗?在您的编辑操作中检查请求是发布请求还是获取请求,然后使用相同的函数定义执行更新和编辑操作.

<前>定义编辑@user = User.find(params[:id])如果 request.post?@user.update_attributes 参数[:user]...别的...结尾结尾

注意:请记住,您永远无法真正对客户端隐藏 POST 操作,因为他们始终可以查看您的源代码并查看您在表单中发布的操作.

I have 2 actions - Edit and Update. Form in Edit submits the values to Update action. When saving a model fails I render edit teplate, where user sees errors and fields are prepopulated with what he filled before. There's a huge but for me - in URL panel in user's browser there's /user/update, even when (and because) I rendered edit template. Can I somehow change that with passing some parameters to render method in update action? I don't want the user to see that there's any (update) action aside of edit. Is it possible?

解决方案

There are two ways around this:

1) Redirect from the update action back to the edit action, instead of just rendering the template, and pass the error messages and attributes that you want to use to populate the object that is being edited. This will result in the URL being /user/edit.

def update
  @user = User.find(params[:id])
  if @user.update_attributes params[:user]
    ...
  else
    redirect_to edit_user_path(@user, :messages => @user.errors)
  end
end

2) Post to the edit action instead of the update action and remove the update action entirely. You can use request.post? in your edit action to check if the request is a post or get request and then perform your update and edit actions using the same function definition.

def edit
  @user = User.find(params[:id])
  if request.post?
    @user.update_attributes params[:user]
    ...
  else
    ...
  end
end

NOTE: Keep in mind though that you can't ever really hide the POST action from the client because they can always view your source code and see the action to which you are posting in your form.

这篇关于渲染模板并在浏览器中更改 url 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆