I'm fairly new to ruby on rails and I'm having some trouble trying to extract a key value from an array of hashes (#sorted) when using options_from_collection_for_select in my html.haml file.
So far I've tried
options_from_collection_for_select(#sorted, "#{#sorted['id']}",
"#{#sorted['name']}")
options_from_collection_for_select(#sorted, #sorted['id'], #sorted['name'])
But both give me a "Can't convert string to integer" error I've tried calling to_i but the error still persists.
Array of Hashes (#sorted)
#sorted => [{"id"=>"51a7ba4154b3289da800000f", "name"=>"Book1", "count"=>8},
{"id"=>"519d24ed54b328e512000001", "name"=>"Book2", "count"=>5},
{"id"=>"5258917b54b32812cd000003", "name"=>"Book3", "count"=>1}]
With options_for_select:
options_for_select(#sorted.map{|hash| [hash["id"],hash["name"]]})
Remember that when you have an array, it is made up of multiple elements, and the methods you call on it are array methods, not methods for the elements inside.
In this case, each element is a hash, so your array looks like the following:
[ {"id" => 1, "name" => "Name 1"}, {"id" => 2, "name" => "Name 2" ]
The class itself is an array. You can index in to an array like so:
myArray[1]
This method takes an integer and finds the nth element. So doing:
#sorted[1]
Would return this hash element:
{"id" => 2, "name" => "Name 2"}
And now you can call hash methods on it. This is why you were getting that error, because the Array#[] method assumed you were giving it an integer to index in to the array, but you were giving it a string - a string that could not be converted in to an integer.
So in your particular case, you probably mean to do:
#sorted.first["id"], #sorted.first["name"]
(Doing #sorted.first is an alternative to #sorted[0] to get the first element in an array)
Related
So I understand that you can update some models using Model.update(ids, values) where ids represent the ID and values represent the actual changes. I do also understand that you can pass in a hash, such as {1 => {column_name: "new value"}, 2 => {column_name: "new value"}} which works just fine.
However, what if, instead of IDs, I wanted to use another column such as uuid? Can I use the .update method in such a way to where it would do something like Model.update(uuid: hash.keys, hash.values)?
It doesn't appear that I can do this with this method, but is there another way that I can do this so that I don't have to iterate through every single key and value in my long array (which contains thousands of keys and values)
This is what happens when I try to implement what I would like to do:
[2] pry(#<MyWorker>)> test = {"b7d720f984abeda37836d07b2147560ce06fb4d7e30fe8d59c1fe610cb440bbf" => {:protocol => "udp", :port => 5}}
=> {"b7d720f984abeda37836d07b2147560ce06fb4d7e30fe8d59c1fe610cb440bbf"=>{:protocol=>"udp", :port=>5}}
[3] pry(#<MyWorker>)> Port.update(uuid: test.keys, test.values)
SyntaxError: unexpected ')', expecting =>
...e(uuid: test.keys, test.values)
... ^
[3] pry(#<MyWorker>)>
As Sebastian Palma said, you can do this using a where clause before the update action like so:
Port.where(uuid: test.keys).update(test.values)
I have a pluck that is turned into a hash and stored in a variable
#keys_values_hash = Hash[CategoryItemValue.where(category_item_id: #category_item.id).pluck(:key, :value)]
If 2 records have the same :key name then only the most recent record is used and they aren't both added to the hash. But if they have the same value and different keys both are added to the hash.
This also occurs if I swap :key and :value around (.pluck(:value, :key)). If they have now the same value it only uses the most recent one and stores that in the hash. But having the same key is now fine.
I'm not sure of this is being caused by pluck or from being sorted in a hash. I'm leaning towards pluck being the culprit.
What is causing this and how can I stop it from happening. I don't want data being skipped if it has the same key name as another record.
I'm not sure why you need convert pluck result into a Hash, because it was an Array original.
Like you have three CategoryItemValue like below:
id, key, value
1, foo, bar1
2, foo, bar2
3, baz, bar3
when you pluck them directly, you will get a array like:
[ ['foo', 'bar1'], ['foo', 'bar2'], ['baz', 'bar3'] ]
but when you convert it into a hash, you will get:
{'foo' => 'bar2', 'baz' => 'bar3' }
because new hash value will override the old one if key ( foo in the example above) exists.
Or you could try Enumerable#group_by method:
CategoryItemValue.where(...).pluck(:key, :value).group_by { |arr| arr[0] }
I have an array of custom objects in it. Those objects have a parameter called name which is a concatenation of 2 strings having a delimiter in between. Eg: name could be Some#Data where 'Some' is first string and 'Data' is another and # is a delimiter.
My intention is update the name parameter for all the objects inside the array such that the param would only have 'Data' (i.e. remove 'Some#') and store the objects inside another array after updating. Below is the code:
final_array = array1.select do |object|
object.name = object.name.match(/#(.*?)$/)
end
When I print object.name.match(/#(.*?)$/) this gives me output as:
#<MatchData "#Data" 1:"Data">
Out of this output, how do I get "Data" from this MatchData. I tried object.name.match(/#(.*?)$/)[1] but it didn't work. Or do I need to change my regex?
I would use #each and #gsub methods:
array.each do |object|
object.name = object.name.gsub(/^.+#/, '')
end
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]=c as a hash [1] where b is a key and c is its associated value: { :a => { :b => "c" } }.
So the url http://localhost:3000/movies?ratings[PG-13]=1&commit=Refresh will result in the hash:
{ :ratings => { :'PG-13' => "1"}, :commit => "Refresh" }
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 if params["ratings"] is present, and it is, so it returns params["ratings"], which is a hash with the key PG-13 and value "1".
[1] Or rather, a HashWithIndifferentAccess, a special kind of hash that converts symbol and string keys into a single type.
I am new to Ruby, and I am having some problems with hashes.
I have XML returned from the YouTube API that I converted into a hash. Here is the hash returned by Hash.from_xml(): http://pastebin.com/9xxE6iXU
I am trying to grab specific elements from the hash for each result, such as the title, link, author, etc. Whenever I try to loop through the hash or grab a specific element, I receive a "can't convert String into Integer" error.
Here is the code I am using for the loop:
#data["feed"]["entry"]["title"].each do |key, value|
"<p>"+key+" "+value+"</p>"
end
I have also tried grabbing specific elements, such as #data["feed"]["entry"]["title"][0].
How do I loop through the hash and grab specific elements out?
That's happening because #data["feed"]["entry"] is array of hashes:
puts #data["feed"]["entry"].class # => Array
Each element-hash inside this array has "id", "category", "title" etc. values.
For grabbing each title try to use following snippet:
#data["feed"]["entry"].each do |entry|
puts entry["title"]
end
# => "TABE test adult basic education"
"WhatCollegesHopeYouWon'tFindOutAboutACTSATTestPrep..."
....