My URL is as follows:
http://localhost:3000/movies?ratings[PG-13]=1&commit=Refresh
I’m experimenting evaluating URL params and am unsure why this works the way is does. In my controller I evaluate the parameters and build an array as follows:
In my View I use the following debug statement to see what gets placed into @selected_ratings
=debug(@selected_ratings)
In my controller I have tried two statements.
Test one returns the following, this should work?
@selected_ratings = (params["ratings[PG-13]"].present? ? params["ratings[PG-13]"] : "notworking")
output: notworking
However if I use the following ternary evaluation n my controller:
@selected_ratings = (params["ratings"].present? ? params["ratings"] : "notworking")
output:!map:ActiveSupport::HashWithIndifferentAccess
PG-13: "1"
Why will my evaluation not find the literal params["ratings[PG-13]"]?
Rails parses string parameters of the form
a[b]=cas a hash [1] wherebis a key andcis its associated value:{ :a => { :b => "c" } }.So the url
http://localhost:3000/movies?ratings[PG-13]=1&commit=Refreshwill result in the hash:In your first assignment, you check if
params["ratings[PG-13]"]is present, and since it is not, it returns “notworking”. In the second case, you check ifparams["ratings"]is present, and it is, so it returnsparams["ratings"], which is a hash with the keyPG-13and value"1".[1] Or rather, a
HashWithIndifferentAccess, a special kind of hash that converts symbol and string keys into a single type.