Why is this find_all method not working rails - ruby-on-rails

I have a method that is suppose to iterate over an array and match any items to a string I have in my model. My method looks like this
#new_array = #old_array.find_all { |t| t.fetch('name') == "self.object_name" }
This method should look thru the array of hashes I have and match any items that have the same name as object_name. When I test the name comparison to the object_name in console it shows true but when I run the full method described above it shows no objects found, however I know the array contains multiple objects with the EXACT same name. Any idea of whats wrong?
The array looks like so...
old_array = {"id"=>"123", "account"=>"456", "name"=>"CITY"},
{"id"=>"456", "account"=>"567", "name"=>"CITY DIR DEP"},
{"id"=>"456", "account"=>"567", "name"=>"BUCK"},
{"id"=>"456", "account"=>"567", "name"=>"CITY DIR DEP"},
{"id"=>"456", "account"=>"567", "name"=>"HAPPY"},
{"id"=>"456", "account"=>"567", "name"=>"CIRCLE"}
and the object prints out in console as
self.object_name => "CITY DIR DEP"

You don't need quotes " at all (you literally trying to compare retrieved name with string "self.object_name" instead of the value of self.object_name):
#new_array = #old_array.find_all { |t| t.fetch('name') == self.object_name }
If you are a big fan, you can interpolate with "#{}":
#new_array = #old_array.find_all { |t| t.fetch('name') == "#{self.object_name}" }

Try this:
#new_array = #old_array.find_all { |t| t['name'] == self.object_name }

Related

Coalesce with baby_squeel / arel in Rails

I am trying to write a rather complicated query using baby_squeel. The query requires the use of the coalesce SQL function. coalesce is used as an example a couple of times on the baby_squeel home page but when I try to use it in a query I get a no method error.
Example below:
result = Table.selecting { |t| [t.col1,
((coalesce(t.col2, 0) + coalesce(t.col3, 0)).sum.as('column'))] }
.where.has { |t| t.col4 == 'some condition' }
.grouping { |t| t.col1 }
I am using Rails 5 and baby_squeel 1.2. The query is called inside of a private controller function.
Why is this happening? Do I need to require something or define the function myself using arel?
Not sure if this will help anyone, but I found what I was missing. Since I gave arity to the block I had to reference the functions I wanted to use with the airty variable in this case t. The correct code is:
result = Table.selecting { |t| [t.col1,
((t.coalesce(t.col2, 0) + t.coalesce(t.col3, 0)).sum.as('column'))] }
.where.has { |t| t.col4 == 'some condition' }
.grouping { |t| t.col1 }

Searching array of objects for item in Ruby

I am trying to search through an array of objects for a value, but am having trouble getting the find_index to work. In my code below, I am trying to search for the name (joseph) in the array. Is this the best way? I want to return that object after I search and find it.
name = "joseph"
array = [{"login":"joseph","id":4,"url":"localhost/joe","description":null},
{"login":"billy","id":10,"url":"localhost/billy","description":null}]
arrayItem = array.find_index {|item| item.login == name}
puts arrayItem
Your array contains a Hash, with keys that are symbols (in hashes, key: value is a shorthand for :key => value). Therefore, you need to replace item.login with item[:login]:
name = "joseph"
array = [{"login":"joseph","id":4,"url":"localhost/joe","description":nil},
{"login":"billy","id":10,"url":"localhost/billy","description":nil}]
arrayIndex = array.find_index{ |item| item[:login] == name }
puts arrayIndex
The code above retrieves the index at which the sought object is in the array. If you want the object and not the index, use find instead of find_index:
arrayItem = array.find{ |item| item[:login] == name }
Also, note that in Ruby, null is actually called nil.

how to get the key value from the nested hash inside the array?

I have a array which is inside a hash. I want know the result of the student (pass/fail) using the following array. First I have to match them with particular standard and compare their marks with the hash pass and fails. And I want to get the key pass or fail based on their mark. How to achieve this using Ruby?
array = [
{
:standard =>1
:pass=>{:tamil=>30,:eng=>25,:math=>35},
:fail=>{:tamil=>10,:eng=>15,:maths=>20}
},
{
:standard =>2,
:pass=>{:tamil=>40,:eng=>35,:math=>45},
:fail=>{:tamil=>20,:eng=>25,:maths=>30}
}
]
#student is assumed to be defined
standard = array.select {|standard| standard[:standard] == #student.standard}
eng_pass = #student.eng_mark >= standard[:pass][:eng]
eng_fail = #student.eng_mark <= standard[:fail][:eng]
return [eng_pass, eng_fail, whatever_else_you_want]
So on and forth for various topics.
The syntax in reading values from this structure is something like:
array[0][:pass][:eng]
and accordingly you can do the comparison as usual in batch:
for i in 0..#students_array.length
num = # student's score
standard = # something like array[0][:pass][:eng]
if num > standard
# something like 'put "You passed!"'
end
end

Getting an indexed hash as a result from activerecord

Is there a way to pull records from activerecord in a hash already indexed by id instead of an array?
This is what im currently doing:
results = {}
Table.select { |current| results[current.id] = current }
Im assuming that there has to be a method that does that?
Table.all.index_by { |t| t.id }
Or:
Table.all.index_by(&:id)
if you're into the whole brevity thing.

Parsing an array of objects by attributes in rails 3.2

Is it possible to parse an array of objects to select them by attribute? I have a situation where I need to display all objects of a model grouped by an attribute on the index page. What I had been doing in my controller is this...
#xx_controller.rb
#group1 = City.where(:population => 'big')
#group2 = City.where(:population => 'medium')
#group3 = City.where(:population => 'small')
But I'd prefer to do something like this in the controller...
#cities = City.all
And in my view something along the lines of a query, rather than prepackaged instance variables -
#cities.where....
Any thoughts?
If you don't mind loading everything at once from the database, you can do:
#cities = City.all.group_by(&:population)
Which returns a hash whose keys are the possible values for the population attribute.
Then, on your view, you can access the cities on each 'group' by doing #cities['small'], #cities['medium'] and so on.
Do you mean something like this?
#cities = City.all
small_cities = #cities.select { |city| city.population == 'small' }
medium_cities = #cities.select { |city| city.population == 'medium' }
big_cities = #cities.select { | city| city.population == 'big' }

Resources