How to retrieve an array of values from an array of ActiveRecord objects with 'each' method? - ruby

I'm trying to perform this non-basic query with Rails :
proj_repartitions = ProjRepartition.includes(:proj_contributions).find( proj_project.proj_charges.each{|pc| pc.proj_repartition_id} )
The point is I need to pass an array of 'ids' to the find method.
I want to extract those 'ids' from an array of ActiveRecord objects where each of these is equipped with an 'id' attribute.
When I try on the Rails console:
proj_project.proj_charges.each{|pc| pc.proj_repartition_id}
I got exactly the same array as proj_project.proj_charges
What am I doing wrong?
=== UPDATE ===
According to the answers, my definitive working code is:
proj_project.proj_charges.collect{|pc| pc.proj_repartition_id}

Instead of using each try map or collect - they should return an array.

Each only executes the do block code for each item but doesn't "save" the return value.
Collect and Map executes the do block code for each item and the return value in an array.
hope that makes sense

proj_project.proj_charges.map(&:proj_repartition_id)
Short way of writing
proj_project.proj_charges.map{|pc| pc.proj_repartition_id}

Related

Access value from a Netsuite hash, Enumerator

Hi I am trying to extract a value from a Netsuite hash inside custom fields, and some others, which typically look like this - `
"custbody_delivery_ticket_number"=>
{
"script_id"=>"custbody_delivery_ticket_number",
"internal_id"=>"2701",
"type"=>"platformCore:DateCustomFieldRef",
"attributes"=> {
"value"=>"123abc"
}
}` and want the value of it inside of attributes.
Have tried many different ways, but one in particular -
delivery_ticket_number: "#{netsuite_sales_orders.custom_field_list.custom_fields.select['custbody_nef_meter_ticket_number']['attributes']['value']}",
throws error for class Enumerator, NoMethodError: undefined method `[]' for #Enumerator:0x00005589ec778730 which indicates may be getting close, but doing something wrong.
If anyone has any idea how to get values from these kind of hashes?
(Am told by the system admin that it is the correct custbody identifier)
Many Thanks
Eventually fixed this, grabbing Netsuite custom fields with a select of script_id by name,and map as below:
delivery_date:netsuite_sales_order.custom_fields_list.custom_fields.select { |field| field.script_id == 'custbody_delivery_date' }.map { |field| field.value }.first
First selecting the script_id by unique name, then mapping to the value. Was able to get any custom field like this, preferable as they can move and might not have the same index if use an index to grab them, fetching an incorrect value. This way ensures getting the correct data even if the item is moved up or down in the custom fields list.
Thanks for everyones help!

Accessing specific attribute of an object

Hello I have the following object
object = [#<ShopifyAPI::DiscountCode:0x000000000e1c78a8 #attributes={"code"=>"Disc2", "amount"=>"1.00", "type"=>"percentage"}, #prefix_options={}, #persisted=true>]
How can I properly access the "code" name of that object?
I have tried object[:code] and object.code but it appears I am overlooking something.
object is an array of ShopifyAPI::DiscountCode.
The best way to access it is
object[0].attributes['code']
If u want code of all the objects available in the array, you could get the array of values by
object.map { |obj| obj.attributes['code'] }
Given that this is an Array of ShopifyAPI::DiscountCodes (which inherit from ActiveResource::Base)
You can call the code method on them. eg:
object[0].code
#=> "Disc2"
object.map(&:code)
#=> ["Disc2"]
First, object is array:
obj0 = object[0]
Second, this is instance variable:
attributes = obj0.instance_variable_get(:#attributes)
Last, gets values by keys:
attributes['code']

Why can't I append an object to an array in rethinkdb?

I am trying to append an object into an array in rethink. Here is how I am trying to append it:
rethink.table('shifts')
.get(shiftId)
.update(row => row("milestones").default([]).append({
dateAchieved: "2017-01-01",
phaseType: "TEST"
})).run(rethinkConnection)
The error I get is this:
first_error: 'Inserted value must be an OBJECT (got ARRAY):\n[\n\t{\n\t\t"dateAchieved":\t"2017-01-01",\n\t\t"phaseType":\t"TEST"\n\t}\n]',
I also tried the same code about, but removed .default([]), which did not change anything.
I have tried logging out what row('milestones') is and this is the result:
var_15("milestone")
I was expecting to see an array. What else is necessary to add an object to an array? How do I make this work?
You need to update document with a document not an array. Your reql should look like this
rethink.table('shifts')
.get(shiftId)
.update({
milestones: rethink.row('milestones').append({
dateAchieved: "2017-01-01",
phaseType: "TEST"
})
})
.run(rethinkConnection)
this is because the .append command does not commit data to the database it only returns an in memory modified array

How to count number of matches using page object?

My application has a list and it's size changes very regularly. So I need to get the li count before starting the test cases. So this is how I used to get the count
b.lis(:xpath => "//ul[#id='global_nav']/li[contains(#id, 'nav-')]").count
Now I need to achieve this in page object way. I declared the list in my page file as below.
list_item(:global_nav_count, :xpath => "//ul[#id='global_nav']/li[contains(#id, 'nav-')]")
If I try to get count as below
page.global_nav_count_element.count
It returns method not found error. Can any one suggest any solution to achieve this in page object way ?
The list_item accessor is similar to Watir's li method in that it returns the first matching element. If you want a collection of elements, you need to tell the page object.
The accessor for a collection of li elements is list_items (note the plural):
list_items(:global_nav_count, :xpath => "//ul[#id='global_nav']/li[contains(#id, 'nav-')]")
The method created to access the collection is also pluralized:
page.global_nav_count_elements.count

How do I extract a value from this Ruby hash?

I'm using the Foursquare API, and I want to extract the "id" value from this hash
[{"id"=>"4fe89779e4b09fd3748d3c5a", "name"=>"Hitcrowd", "contact"=>{"phone"=>"8662012805", "formattedPhone"=>"(866) 201-2805", "twitter"=>"hitcrowd"}, "location"=>{"address"=>"1275 Glenlivet Drive", "crossStreet"=>"Route 100", "lat"=>40.59089895083072, "lng"=>-75.6291255071468, "postalCode"=>"18106", "city"=>"Allentown", "state"=>"Pa", "country"=>"United States", "cc"=>"US"}, "categories"=>[{"id"=>"4bf58dd8d48988d125941735", "name"=>"Tech Startup", "pluralName"=>"Tech Startups", "shortName"=>"Tech Startup", "icon"=>"https://foursquare.com/img/categories/shops/technology.png", "parents"=>["Professional & Other Places", "Offices"], "primary"=>true}], "verified"=>true, "stats"=>{"checkinsCount"=>86, "usersCount"=>4, "tipCount"=>0}, "url"=>"http://www.hitcrowd.com", "likes"=>{"count"=>0, "groups"=>[]}, "beenHere"=>{"count"=>0}, "storeId"=>""}]
When I try to extract it by using ['id'], I get this error can't convert Symbol into Integer. How do I extract the value using ruby? Also, how do I do this for multiple hashes extracting the "id" value each time?
Please pardon my inexperience. Thanks!
It's wrapped in an array, that's what the [ and ] mean on the start and end. But it also looks like this array only one object in it, which is the hash you really want.
So assuming you want the first object in this array:
mydata[0]['id'] # or mydata.first['id'] as Factor Mystic suggests
But usually when an API returns an Array there is a reason (it might return many results instead of just one), and naively plucking the first item from it my not be what you want. So be sure you are getting the kind of data you really expect before hard coding this into your application.
For multiple hashes, if you want to do something with the id (run a procedure of some kind) then
resultsArray.each do |person|
id = person["id"] #then do something with the id
end
If you want to just get an array containing the ids then
resultsArray.map{|person| person["id"]}
# ["4fe89779e4b09fd3748d3c5a", "5df890079e4b09fd3748d3c5a"]
To just grab the one item from the array, see Alex Wayne's answer
To get an array of ids, try: resultsArray.map { |result| result["id"] }

Resources