2014-03-18 104 views
25

我收到像一個JSON包:強大的參數需要多個

{ 
    "point_code" : { "guid" : "f6a0805a-3404-403c-8af3-bfddf9d334f2" } 
} 

我想告訴大家,既point_code和​​是必需的,而不是僅僅允許軌。

此代碼似乎工作,但我不認爲這是很好的做法,因爲它返回一個字符串,而不是完整的對象:

params.require(:point_code).require(:guid) 

任何想法如何,我可以做到這一點?

回答

23

我也有類似的需要,我所做的就是

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 
+0

這是正確的答案!爲我工作(儘管我必須將第一行中的'require'分隔爲兩個'params.require()'調用 – FloatingRock

+5

不起作用,因爲它會導致錯誤:private方法'require'調用「xxxxxxxx 「:字符串 – zuba

+1

@FloatingRock:在我的情況下要求身體像 { 「ID」:123, 「名」: 「富」, 「吧」: 「foobar的」 } 如何要求所有PARAMS –

1

require取一個參數。因此,除非您覆蓋require方法,否則無法傳遞多個密鑰。你可以達到你想要的東西在你的動作有一些附加邏輯:

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? 

    <do your stuff> 
end 

def point_params 
    params.permit(point_code: :guid) 
end 
4

OK ,不漂亮,但應該做的伎倆。假設你有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。使用相同的參數obj,您需要依次鍵入每個鍵,並最終返回對象。不漂亮,但適合我。

+1

此代碼相當於'def thing_params; params.require(:baf); end'。請參閱Vox的[上述評論](https:/ /stackoverflow.com/questions/22487878/strong-parameters-require-multiple#comment67090809_24411532)。 – James

相關問題