获取在 Rails 中更新时保留的参数
以 Post 作为示例模型,假设 Post 有 2 个属性,这两个属性都有验证。当要编辑一篇文章时,假设我更改了 2 个属性,其中一个属性验证失败,导致页面重新加载。在我看来,当重新加载页面时,以前保存的帖子属性版本会显示在表单中,而不是我刚刚输入的属性,尽管我刚刚输入的属性位于参数中。
这将在典型的创建操作中处理,因为 post 实例变量声明将如下所示:
@post = Post.new(params[:post])
但是,在更新操作中,post 实例变量如下所示:
@post = Post.find(params[:id])
因此,输入到表单中的更改(传递到参数中)不会被更改。重新呈现在表单上。我是否正确描述了这一点?如果是,有没有办法在验证失败时使用表单呈现更改?或者也许,只有不会失败验证的更改?
Taking Post as an example model, let's say Post has 2 attributes, both of which have validations. When going to edit a post, say I change the 2 attributes, and one fails validation, causing the page to be reloaded. It appears to me that when the page is reloaded, the previously saved versions of the post's attributes are displayed in the form, and not the attributes I just entered, though the ones I just entered are in the params.
This would be handled in typical create actions because the post instance variable declaration would look like this:
@post = Post.new(params[:post])
However, in update actions, the post instance variable looks like this:
@post = Post.find(params[:id])
Therefor, the changes entered into the form, which are passed into the params are not re-rendered on the form. Am I describing this correctly, and if so, is there a way I can get the changes to be rendered with the form when validation fails? Or perhaps, only the changes which don't fail validation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 corey 所说,您需要在更新时更新属性,因此:
@post = Post.find(params[:id])
您当前没有更新 post 的实例,因此您可以看到数据库中的内容。
as corey says you need to update the attributes on update so:
@post = Post.find(params[:id])
you are currently not updating the instance of post, so you see what is in the database.