Ruby on Rails:如何在redirect_to上保留验证错误,而不在cookie中存储太多内容
我试图在我的控制器中使用redirect_to,同时仍然保留验证错误闪存消息。在该网站的另一篇文章中,建议的答案是使用:
flash[:error] = @object.errors CookieOverflow
不幸的是,如果有很多错误(在我的例子中为 10 个),我会得到一个 ActionDispatch::Cookies:: 错误,因为显然 @object.errors 对象太大而无法存储在 cookie 中。
我真的很想使用重定向而不是渲染,因为它们的复杂性我没有提到其他原因。
有什么建议吗?
I'm trying to use a redirect_to in my controller while still keeping the validation error flash messages. In another post on this site, the suggested answer was to use:
flash[:error] = @object.errors
redirect_to object_path
Unfortunately, if there are many errors (10 in my case), I get a ActionDispatch::Cookies::CookieOverflow
error, since apparently the @object.errors object is too large to store in the cookie.
I'd really like to use redirect instead of render for other reason I have not mentioned due to their intricacy.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用 activerecord 存储而不是 cookie 存储,因为后者无法存储大对象。
config/initializers/session_store.rb:
然后
这应该可以解决你的问题
You should use the activerecord store instead of cookie store as the latter cannot store large objects.
config/initializers/session_store.rb:
And then
That should solve your problem
仅存储错误消息,而不存储对象,例如。
@object.errors.full_messages
。Store only the error messages, rather than the objects eg.
@object.errors.full_messages
.您可以在 cookie 中存储的内容有 4kb 的限制,当 Rails 将您的对象转换为文本以写入 cookie 时,它可能会大于该限制。
Ruby on Rails ActionDispatch::Cookies::CookieOverflow 错误
这样就会发生 CookieOverflow 错误。
解决这个问题最简单的方法是,您需要更改 session_store 并且不要使用 cookie_store。您可以通过示例使用 active_record_store 。
以下是步骤
生成创建会话表的迁移
rake db:sessions:create
运行迁移
rake db:migrate
修改 config/initializers/session_store.rb from
(App)::Application.config.session_store :cookie_store, :key => 'xxx'
到
(App)::Application.config.session_store :active_record_store
完成这三个步骤后,重新启动应用程序。 Rails 现在将使用会话表来存储会话数据,
而且你不会有 4kb 的限制。
You've got a 4kb limit on what you can store in a cookie, and when Rails converts your object into text for writing to the cookie its probably bigger than that limit.
Ruby on Rails ActionDispatch::Cookies::CookieOverflow error
That way this CookieOverflow Error occurs.
The easiest way to solve this one is, you need change your session_store and don't use the cookie_store. You can use the active_record_store by example.
Here is the steps
Generate a migration that creates the session table
rake db:sessions:create
Run the migration
rake db:migrate
Modify config/initializers/session_store.rb from
(App)::Application.config.session_store :cookie_store, :key => 'xxx'
to
(App)::Application.config.session_store :active_record_store
Once you’ve done the three steps, restart your application. Rails will now use the sessions table to store session data,
and you won’t have the 4kb limit.