Ruby On Rails: Accessing Array? - ruby-on-rails

I have an array stored in a variable temp which looks like this:
temp.inspect output :
[#"Marlana Letelier", "completed_at"=>nil, "status"=>"incomplete", "name"=>nil, "lead_move_date"=>"2012-06-17 00:00:00", "archive_time"=>nil, "stop_time"=>nil, "priority"=>"2", "assigned_to_user_firstname"=>"Vanessa", "notes"=>"", "created_by_id"=>nil, "id"=>"804005", "assigned_to_id"=>"1", "dn_email_id"=>nil, "outcomes_string"=>"other", "lead_id"=>"101139", "flavor"=>"PhonecallTask", "stringified_parameters"=>"{\n'purpose' => 'continued contact attempt',\n'phone_number' => '361-946-9905',\n}", "created_at"=>"2011-12-21 13:29:07", "start_time"=>"2012-04-04 17:00:00"}>]
temp.class specifies it as an array but temp[1] doesn't output anything.
How do I access the elements ?
EDIT:
1) Temp either had nothing, 1 object or multiple objects
2) Check for nil
3) Get each object out
4) access the attributes

Although your inspect output looks wrong (I think you're missing some text that came out in <...> tags) it looks like you have an array with a single item. Verify this assumption by outputting temp.length.
Since Arrays in Ruby are 0-indexed, try temp[0] or temp.first.

Related

Rails params to array

I am sending a list of checkbox selected from PHP file to our Rails API server. All checked items' ID's will be sent in json format (campaign_ids in json_encode from PHP):
I got a URL being passed to our API like this
Started PUT "/campaigns/function.json?campaign_ids=["6","7"]&user_id=0090000007"
I need to get the campaign_ids ["6","7"] and process it like any other array using array.each do || end
How can I convert this to an array so I can use array.each?
The following sample code can achieve it but I think there could be a better way?
campaign_ids = params[:campaign_ids].to_s # [\"6\",\"7\"]
campaign_ids = campaign_ids.gsub(/[^0-9,]/,'') # 6,7
if campaign_ids.size.to_i > 0 # 3 ??
campaign_ids.split(",").each do |campaign_id|
...
end
end
The correct format of the URL should've been campaign_ids[]=6&campaign_ids[]=7. That would automatically yield an array of [6, 7] when you do params[:campaign_ids].
But assuming you can't change the format of the incorrect parameters, you can still get it via JSON.parse(params[:campaign_ids])
Try this
campaign_ids = JSON.parse(params[:campaign_ids])
You get params[:campaign_ids] as a string.
So, you will have to parse that json string to get array elements.
params[:campaign_ids] is already in your desired array format, you need not convert that to string using to_s.
You can do something like this
campaign_ids = params[:campaign_ids]
campaign_ids.each do |campaign_id|
# do the computation here
end

Generation of table and accessing elements of a Array of Hashes

I have the following Array of hashes in a rails application:
a = ["{\"ROW1\"=>{\"correct\"=>{\"h\"=>\"10\", \"m\"=>\"11\", \"l\"=>
\"12\"}, \"wrong\"=>{\"h\"=>\"2\", \"m\"=>\"2\", \"l\"=>\"4\"}, \"blank
\"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"3\"}}, \"ROW2\"=>{\"correct
\"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"4\"}, \"wrong\"=>{\"h
\"=>\"4\", \"m\"=>\"6\", \"l\"=>\"6\"}, \"blank\"=>{\"h\"=>\"7\",
\"m\"=>\"5\", \"l\"=>\"6\"}}, \"ROW3\"=>{\"correct\"=>{\"h\"=>\"4\",
\"m\"=>\"6\", \"l\"=>\"7\"}, \"wrong\"=>{\"h\"=>\"6\", \"m\"=>\"7\",
\"l\"=>\"5\"}, \"blank\"=>{\"h\"=>\"7\", \"m\"=>\"9\", \"l\"=>
\"3\"}}}"]
I want to access its elements and create a database table from it, in the following format
ROW1 correct h=10, m=11,l=12
wrong h=2, m=2,l=4
blank h=2, m=4,l=3
...and similar for ROW2 and ROW3.
How can I do that?
I tried to access a value using
a["ROW1"]["Correct"]["h"]
...but it returns a nil value.
How to access the values of this array of hashes?
you need to first convert the string to hash which can be done as follows:
require 'json'
a = ["{\"ROW1\"=>{\"correct\"=>{\"h\"=>\"10\", \"m\"=>\"11\", \"l\"=>
\"12\"}, \"wrong\"=>{\"h\"=>\"2\", \"m\"=>\"2\", \"l\"=>\"4\"}, \"blank
\"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"3\"}}, \"ROW2\"=>{\"correct
\"=>{\"h\"=>\"2\", \"m\"=>\"4\", \"l\"=>\"4\"}, \"wrong\"=>{\"h
\"=>\"4\", \"m\"=>\"6\", \"l\"=>\"6\"}, \"blank\"=>{\"h\"=>\"7\",
\"m\"=>\"5\", \"l\"=>\"6\"}}, \"ROW3\"=>{\"correct\"=>{\"h\"=>\"4\",
\"m\"=>\"6\", \"l\"=>\"7\"}, \"wrong\"=>{\"h\"=>\"6\", \"m\"=>\"7\",
\"l\"=>\"5\"}, \"blank\"=>{\"h\"=>\"7\", \"m\"=>\"9\", \"l\"=>
\"3\"}}}"
]
hash_string = a[0]
hash = JSON.parse hash_string.gsub("\n", '').gsub('=>', ':')
# you access the hash now:
hash["ROW1"]["correct"]["h"]
# => 10
Btw, please note that there is a typo. Instead of Correct, the key is correct with small c instead of capital C.
Hope it helps : )

Ruby, accessing a nested value in a hash

I have the following hash. Using ruby, I want to get the value of "runs". I can't figure out how to do it. If I do my_hash['entries'], I can dig down that far. If I take that value and dig down lower, I get this error:
no implicit conversion of String into Integer:
{"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588, ...
Assuming that you want to lookup values by id, Array#detect comes to the rescue:
h = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]}]}
# ⇓⇓⇓⇓⇓⇓⇓ lookup element with id = 7
h['entries'].detect { |e| e['id'] == 7 }['runs']
.detect { |e| e['id'] == 2588 }
#⇒ { "id" => 2588 }
As you have an array inside the entries so you can access it using an index like this:
my_hash["entries"][0]["runs"]
You need to follow the same for accessing values inside the runs as it is also an array.
Hope this helps.
I'm not sure about your hash, as it's incomplete. So , guessing you have multiple run values like:
hash = {"id"=>2582, "entries"=>[{"id"=>"7", "runs"=>[{"id"=>2588}]},
{"id"=>"8", "runs"=>[{"id"=>2589}]},
{"id"=>"9", "runs"=>[{"id"=>2590}]}]}
Then, you can do
hash["entries"].map{|entry| entry["runs"]}
OUTPUT
[[{"id"=>2588}], [{"id"=>2589}], [{"id"=>2590}]]

Map object and nested object to model using Ruby on Rails

I have an object like
{"Result":[{
"Links":[{
"UrlTo":"http://www.example.com/",
"Visited":1364927598,
"FirstSeen":1352031217,
"PrevVisited":1362627231,
"Anchor":"example.com",
"Type":"Text",
"Flag":[],
"TextPre":"",
"TextPost":""
}],
"Index":0,
"Rating":0.001416,
"UrlFrom":"http://www.exampletwo.com",
"IpFrom":"112.213.89.105",
"Title":"Example title",
"LinksInternal":91,
"LinksExternal":51,
"Size":5735
}]}
And I have a model with all of the keys.
UrlTo, Visited, FirstSeen, PrevVisited, Anchor, Type, TextPre, TextPost, Index, Rating, UrlFrom, IpFrom, Title, LinksInternal, LinksExternal, Size
I understand how to save this to the database without this bit below...
"Links":[{
"UrlTo":"http://example.com/",
"Visited":1364927598,
"FirstSeen":1352031217,
"PrevVisited":1362627231,
"Anchor":"example.com",
"Type":"Text",
"Flag":[],
"TextPre":"",
"TextPost":""
}],
Not sure how to save it with a nested object as well.
I had a search on Google and SO and couldn't find anything, what is the correct way to do this? Should I move the nested object into the one above? I have no need for it to be nested...
Thanks in advance
it looks like you want to save links, so I would loop over the Result/Links in the json provided, and create a new hash based on the links.
I've pretended below that your json is in a file called input.json -- but you'd obviously just parse the text or use an existing JSON object
require 'json'
json = JSON.parse File.read("input.json")
links = json["Result"].map do |result|
result["Links"].map {|link| link }
end.flatten
hash = {"Links" => links}
puts hash
This creates the object:
{"Links"=>[{"UrlTo"=>"http://www.example.com/", "Visited"=>1364927598, "FirstSeen"=>1352031217, "PrevVisited"=>1362627231, "Anchor"=>"example.com", "Type"=>"Text", "Flag"=>[], "TextPre"=>"", "TextPost"=>""}]}

Error trying to Find_by_id, an extra value appears (Ruby on Rails)

I have a POST method that return this:
Request Parameters:
{"cm_test_ids"=>["1",
"8",
"9",
"10",
"11"],
"commit"=>"Create",
"authenticity_token"=>"WiBZQcZt2/Vi2RiFdFtaXnthClLsMubXe6sAhUzOPo8=",
"id"=>"1",
"cm_test_campaigns_object"=>{"cm_test_campaign_id"=>"1",
"comments"=>"",
"assigned_to_id"=>"6"}}
In my controller app I get the "cm_test_ids" like:
#ids_selected = params[:cm_test_ids]
In this point I have no problem, I'm able to save these ids (1,8,9,10,11) in a relation table but if I try to do this:
#my_tests = CmTest.find(["id IN (?)", #ids_selected])
I get this error:
"Couldn't find all CmTests with IDs (0,1,8,9,10,11) (found 5 results, but was looking for 6)"
The value "0" it doens't exits, I've print the array #ids_selected and I dont see it, I dont know why always in the IDs array is added a "0" in the first position, any idea?
You can try this:
CmTest.find_all_by_id(#ids_selected)
Rails generates a hidden field before every multi-select:
https://github.com/rails/rails/issues/5402
It looks like the blank string is being cast to an integer somewhere, which would give you a zero. You might need to strip this out of your parameters.
The error is "solved" using
CmTest.find_all_by_id(#ids_selected)
but find still return nil, I think I found the problem, the query generated have a lot of "\n" :
SELECT * FROM `cm_tests` WHERE (`cm_tests`.`id` IN ('id IN (?)','--- \n- \"1\"\n- \"8\"\n- \"9\"\n- \"10\"\n- \"11\"\n'))
You may also try
CmTest.where(id: #ids_selected )

Resources