Is there a better way to check for items_attributes than the following code? I have to check params[:order] first since sometimes that may not exist, but I hate the look of the long conditional.
if params[:order] and params[:order][:items_attributes]
UPDATE for ruby 2.3, now you can use the dig method
params.dig(:order, :item_attributes)
You can create helper method for easier work with nested hashes. Create ruby_ext.rb file in your lib folder, and write this function:
module RubyExt
module SafeHashChain
def safe(*args)
if args.size == 0 then self # Called without args ...
elsif args.size == 1 then self[args[0]] # Reached end
elsif self[args[0]].is_a?(Hash) then self[args[0]].safe(*args[1..-1])
else nil end # Reached end-value too soon
end
end
end
class Hash; include RubyExt::SafeHashChain; end
After this you can call safe method on nested hashes like this:
params.safe(:order,:items_attributes)
It will return value from items_attributes. If order or items_attributes don`t exist it will return nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With