Make new array in controller by finding id - ruby-on-rails

I have an array with Product Ids and Color HEX Codes
Input:
#campaign.selectedproducts
Output:
["2,333333","1,333333",4,444444"]
I'm trying to make a new array with all of the product data by finding it with id:
#selectedgifts = #campaign.selectedproducts.collect [{|i| Product.find(i) }, |i| i.split(',').last]
Array should output
["Product Object, HEX code", "Product Object, HEX code"]
¿Any help?
Thanks!

You can try with group_by method like below:
#campaign.selectedproducts.group_by(&:color_code).transform_values{|val| val.pluck(:id).uniq}

Converting Product object to string is not what you want i guess. So i suggest you storing each element as hash instead of string.
#campaign.selectedproducts.map do |string|
id, hex_code = string.split(',')
product = Product.find(id)
{ product => hex_code }
end
Edit: Or you can store each element as array like this:
#campaign.selectedproducts.map do |string|
id, hex_code = string.split(',')
product = Product.find(id)
[product, hex_code]
end

Related

how to concat string to array element in rails

I have an array as
["first_name"]
and I want to convert it to
["user.first_name"]
I cannot figure out how I can do this in rails.
If you would like to append text to the values you have in a array you're going to probably want to loop through the data and append to each element in the array like so:
my_array = ["test", "test2", "first_name"]
new_array = my_array.collect{|value| "user.#{value}" }
new_array will now be:
["user.test", "user.test2", "user.first_name"]
You could also just overwrite your original array by using collect! like so
my_array = ["test", "test2", "first_name"]
my_array.collect!{|value| "user.#{value}" }
This will of course overwrite your original original data in my_array
If you would like to just change one value in the array you could use the index of that array and assign the value
my_array = ["test", "test2", "first_name"]
my_array[1] = "user.#{my_array[1]}}
my_array will now read:
["test", "user.test2", "first_name"]
Supposing you've multiple elements in your array, I recommend using .map.
It allows you to iterate the array elements, and return a new value for each of them.
%w[first_name last_name email].map do |attr|
"user.#{attr}"
end
# => [user.first_name, user.last_name, user.email]

change hash key through function call

I have a hash where the keys are country_id's and I would like to change the country_id keys to actually have the name of the country. I have a function that can do the id to name conversion but I can't figure out how to get the keys updated and mapped correctly to their current values.
Also I'm not able to use transform_keys due to the version of ruby\rails I'm on.
I don't know what country will be selected so I need a way of looping through the keys and updating them, then storing back to the hash or a new hash with the values mapped correctly.
the hash I have is called #trending_countries the keys are currently the country_id that needs to be updated and the value consists of a count for that particular country.
#trending_countries = {22=>2, 34=>3} and I would like it in the format of #trending_countries = {United States=>2, Canada=>3}
I tried doing the below in my controller
#trending_countries.each {|k, v| #trending_countries[k] = Country.get_country_name(k)}
the function doing the id to name conversion is in a separate model called Country.
# returns the country name when a country id is given.
def self.get_country_name(country_id)
country = self.find_by(id: country_id)
return country.name
end
One way to do it is the following:
old_hash.map { |key, value| [Country.get_country_name(key), value] }.to_h
old_hash = { 62=>:wee, 12=>:big, 8=>:medium }
country_id_to_name = { 62=>"Monaco", 8=>"France", 12=>"China" }
old_hash.each_with_object({}) { |(k,v),h| h[country_id_to_name[k]] = v }
#=> {"Monaco"=>:wee, "China"=>:big, "France"=>:medium}

Generate a Key, Value JSON object from a Ruby Object Array

I have a Ruby array of students. Student class has attributes id, name and age.
students = [
{id:"id1",name:"name1",age:"age1"},
{id:"id2",name:"name2",age:"age2"},
{id:"id3",name:"name3",age:"age3"}
]
I want to create a JSON key value object from this array as follows.
json_object = {id1:name1, id2:name2, id3:name3}
input = [ {id:"id1",name:"name1",age:"age1"},
{id:"id2",name:"name2",age:"age2"},
{id:"id3",name:"name3",age:"age3"}]
require 'json'
JSON.dump(input.map { |hash| [hash[:id], hash[:name]] }.to_h)
#⇒ '{"id1":"name1","id2":"name2","id3":"name3"}'
Give this a go:
students = [
{id:"id1",name:"name1",age:"age1"},
{id:"id2",name:"name2",age:"age2"},
{id:"id3",name:"name3",age:"age3"}
]
json_object = students.each_with_object({}) do |hsh, returning|
returning[hsh[:id]] = hsh[:name]
end.to_json
In console:
puts json_object
=> {"id1":"name1","id2":"name2","id3":"name3"}
Your data is all identical, but if you wanted to generate a hash that took the value of students[n][:id] as keys and students[n][:name] as values you could do this:
student_ids_to_names = students.each_with_object({}) do |student, memo|
memo[student[:id]] = student[:name]
end
For your data, you'd end up with only one entry as the students are identical: { "id1" => "name1" }. If the data were different each key would be unique on :id.
Once you have a hash, you can call json_object = students_ids_to_names.to_json to get a JSON string.

How can I get the value of the name only on this array?

This is the output array when I do
result = JSON.parse(response.body)
result.values.each {|element|
puts element
}
Result:
{"id"=>3, "code"=>"3", "name"=>"Market", "status"=>"A", "refcode"=>"001"}
{"id"=>4, "code"=>"4", "name"=>"Mall", "status"=>"A", "refcode"=>"002"}
From this array, I only want to get the name value. I tried this
puts result['data'][0]['name'] and it worked fine but I want to get all the name in the array
This is my expected output
Market
Mall
Try using Array#map and over each element, to access it's 'name' key, like:
p array.map { |element| element['name'] }
# ["Market", "Mall"]
I think it'd be something like:
result = JSON.parse(response.body)
result.values.map { |element| element['name'] }
# ["Market", "Mall"]
Since with each and puts you're only iterating and printing the hashes in the array, you could access the 'name' key from result.values.
I wont modify much. Since your name element is at position 3. access it like array because you are using values.each
result = JSON.parse(response.body)
result.values.each {|element|
puts element[2]
}

How to insert an array to an existing hash array in Ruby?

I have a current array of the below hash map, i have another array that i would like to insert into each hash by matching on the id.
{"url"=>"http://ubuntu64:1990/getpages",
"id"=>"32794",
"version"=>"2",
"title"=>"Creating a page",
"space"=>"test",
"parentId"=>"32782",
"permissions"=>"0"}
The other array i want to add the 'imageurl' key/value based on the id, so something like (if id == id insert 'imageurl'/'someurl.jpg}
{"id"=>"32794", "imageurl" => "someurl.jpg}
array = [...] #Declare your array with the "big" hashes here
array2 = [...] #Declare your array with the hash containing the imageurl key here
array.each do |a|
array2.each do |a2|
if a[:id] == a2[:id]
a[:imageurl] = a2[:imageurl]
break #We found it
end
end
end
Should do the trick ... maybe there's a smarter way to do it though

Resources