开发者

Searching in a subhash with Ruby on Rails

I have a hash of hashes like so:

Parameters: {"order"=>{"items_attributes"=>{"0"=>{"product_name"=>"FOOBAR"}}}}

Given that the depth and names of the keys may change, I need to be able to extract the value of 'product_name' (in this example "FOOBAR") with some sort of search or select method, but I cannot seem to figure it out.

An added complication is that Params is (I th开发者_开发百科ink) a HashWithIndifferentAccess

Thanks for your help.


Is this what you mean?

if params.has_key?("order") and params["order"].has_key?("items_attributes") then
    o = params["order"]["items_attributes"]
    o.each do |k, v|
        # k is the key of this inner hash, ie "0" in your example
        if v.has_key?("product_name") then
            # Obviously you'll want to stuff this in an array or something, not print it
            print v["product_name"] 
        end
    end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜