Rake: How to get a value from PGResult

I am using a ActiveRecord::Base to get some values from database. The result of this query is below:


{"parent_id"=>"4", "id"=>"3"}
{"parent_id"=>"10", "id"=>"23"}
{"parent_id"=>"13", "id"=>"29"}  
{"parent_id"=>"15", "id"=>"35"}   

Now, I need to get a id from parent_id. Example, I want to find how is the id associate to parent_id.

It's possible to do it?


I have several hashes from PG::Result. I need to use the first key (parent_id) to get the second key (id).

Example: I need to know how is the id from parent_id = 4. In this case, will be 3.

I think the I need something like this:

  • "4" => 3
  • "10" => 23
  • "13" => 29


I hope I understood your question correctly.

I'm assuming parent_id and id are fields that belong to some model and the result you posted is a result of a query to that model.

Say, you store the result of your query in a variable named res and the input value for parent_id is pid, then try the following. It should give you the id value corresponding to the parent_id submitted as input variable named pid.

res.find_by(parent_id: pid).id

Hope that helps.

Need Your Help

How to make sure another (new) page is not shown when submitting a form

javascript jquery html forms

For an assignment I need to have a table made up of JSON data gotten from a server through an AJAX GET request. Also I have to have an extra row to be able to fill in some extra data as well, this ...

Same address for static variable but different for local variable

c memory memory-management operating-system

I am trying to learn operating systems. At present i am in virtual addressing. What book says that if we have one static variable and one local variable and we update them and sleep for some time a...