Rails 4 强参数 - 处理缺失的模型参数哈希 [英] Rails 4 Strong Parameters - Handling Missing Model Params Hash

查看:51
本文介绍了Rails 4 强参数 - 处理缺失的模型参数哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

型号:帖子和用户

发布属于_to :user
用户 has_many :posts

Post belongs_to :user
User has_many :posts

简单.

假设存在一些用户,我们访问帖子的编辑页面.

Assuming a few users exist, we visit the edit page for a Post.

<%= form_for @post do |f| %>

...

<% User.all.each do |user| %>
  <div><%= f.radio_button "user_id", user.id %></div>
<% end %>

...

Post 的控制器利用 Rails 4 强参数.

The Post's Controller leverages Rails 4 strong parameters.

params.require(:post).permit(:user_id)

假设编辑帖子表单只有单选按钮作为字段.

Assume the edit post form only has the radio buttons as fields.

问题:抛出 ActionController::ParameterMissing 异常.未找到参数:发布

原因是 Post params 哈希从未创建,导致抛出上述异常.例如,与空文本字段不同,空单选按钮不会触发要创建的模型的参数哈希.

The reason being the Post params hash is never created, causing the above exception to be thrown. Empty radio buttons, unlike empty text fields for example, do not trigger the model's param hash to be created.

如果 Post 模型要求 user_id 有效怎么办?当然,由于无法保存 Post 的原因,人们会想要再次渲染视图.

What if the Post model requires a user_id to be valid? Certainly one would want to render the view again with the reason why the Post can't be saved.

问题:在坚持 Rails 惯例的同时处理这种情况的优雅方法是什么?

更新:

进一步集思广益,我相信可能还有很多其他情况会导致此问题;它不一定对应于单选按钮.

Brainstorming about this further, I'm sure there are probably plenty of other situations which generate this problem; it does not necessarily correspond to radio buttons.

推荐答案

我有一个类似的问题,不太喜欢这两个答案中的任何一个.在 Rails 文档中(http://guides.rubyonrails.org/action_controller_overview.html#more-示例) 我看到以下解决方案:

I have a similar problem, and didn't like either of these answers much. In the rails documentation (http://guides.rubyonrails.org/action_controller_overview.html#more-examples) I see the following solution:

params.fetch(:blog, {}).permit(:title, :author)

实际上,您提供的是 {} 的默认值,它似乎工作得很好(至少对于我的情况).

Effectively you are supplying a default of {}, which seems to work well enough (at least for my situation).

应用于您的代码,您将:

Applying to your code, you'd have:

params.fetch(:post, {}).permit(:user_id)

我认为这相当干净,并且似乎在我的代码中工作.

I think this is reasonably clean, and seems to work in my code.

这篇关于Rails 4 强参数 - 处理缺失的模型参数哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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