获取在 Rails 中更新时保留的参数

发布于 2025-01-04 19:15:52 字数 439 浏览 4 评论 0原文

以 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怎樣才叫好 2025-01-11 19:15:52

正如 corey 所说,您需要在更新时更新属性,因此:

@post = Post.find(params[:id])

if @post.update_attributes(params[:post])
  redirect_to post_path(@post)
else
  render :new
end

您当前没有更新 post 的实例,因此您可以看到数据库中的内容。

as corey says you need to update the attributes on update so:

@post = Post.find(params[:id])

if @post.update_attributes(params[:post])
  redirect_to post_path(@post)
else
  render :new
end

you are currently not updating the instance of post, so you see what is in the database.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文