强参数需要多个
我收到的JSON包如下:
{ "point_code" : { "guid" : "f6a0805a-3404-403c-8af3-bfddf9d334f2" } }
我想告诉Rails, point_code
和guid
都是必需的,而不仅仅是允许的。
这段代码似乎有用,但我不认为这是好习惯,因为它返回一个字符串,而不是完整的对象:
params.require(:point_code).require(:guid)
我有什么想法可以做到这一点?
我有类似的需求,我做的是
def point_code_params params.require(:point_code).require(:guid) # for check require params params.require(:point_code).permit(:guid) # for using where hash needed end
例:
def create @point_code = PointCode.new(point_code_params) end
好吧,不是很漂亮,但应该做的伎俩。 假设你有params:foo,:bar和:baf你想要所有的东西。 你可以说
def thing_params [:foo, :bar, :baf].each_with_object(params) do |key, obj| obj.require(key) end end
each_with_object
返回obj,它被初始化为params。 使用相同的params obj,你依次需要每个键,最后返回对象。 不漂亮,但适合我。
截至2015年(RoR 5.0+),您可以将一组键传递给rails中的require
方法:
params.require([:point_code, :guid])
http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require
require
需要一个参数。 因此,除非重写require
方法,否则无法传递多个键。 您可以通过操作中的其他逻辑实现所需的function:
def action raise ActionController::ParameterMissing.new("param not found: point_code") if point_params[:point_code].blank? raise ActionController::ParameterMissing.new("param not found: guid") if point_params[:point_code][:guid].blank? end def point_params params.permit(point_code: :guid) end
这个问题出现在我的谷歌搜索不同的情况,即,当使用“倍数:真”时,如:
<%= form.file_field :asset, multiple: true %>
这与问题完全不同。 但是,为了帮助这里,Rails 5+中的一个工作示例是:
form_params = params.require(:my_profile).permit({:my_photos => []})