Rake: How to get a value from PGResult - ruby-on-rails

I am using a ActiveRecord::Base to get some values from database. The result of this query is below:
Result:
{"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?
Update
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.

Related

Two way lookup of id vs name ruby

I have a hash in which id is the key and name is the value. Both id and value are unique.
Something like this:
h[1] = "ABC"
h[3] = "DEF"
So, if I am given the key of 1, I can easily return a value "ABC".
I need to do a reverse lookup as well, which means if I am given a value of "DEF", I should return 3.
Also, instead of a single value or single key to do the lookup,
I may be provided with an array of values or array of keys instead.
Should I implement two hashes, one for each, or is there any other way in ruby or rails to achieve that?
Edit: This question is not related to finding a key by its value in a hash. It is related to doing a two way lookup not in O(n) time with a better method other than creating two separate hashes.
You can use Hash#invert as below,
reversed_h = h.invert
reversed_h['DEF']
# => 3
You can get your key this way:
hash.key(value) => key
Hash#key
h = { 1 => 'ABC', 3 => 'DEF' }
puts h.key('DEF')
#=> 3

Rails & mongoid - Get distinct values and their ID

I have a mongoDB database with movie. Each document has a movie name, an ID, and tags. I want to display all the unique tag values in a dropdown list and to also be able to click on the tag and be able to show all the movies it is related to. To do that I need the ID associated with the movie.
I'm able to display all the unique movies using this: Movies.distinct(:Tags).each {|x| puts x }
I've tried Movies.distinct(:Tags).each {|x| puts x._id }, this came up with an error.
Now how do I extract the ID value from x?
EDIT:
The document is structured like so
[ _id: Integer, movie: String, tags: Array ]
UPDATE:
Maybe a simpler question... if i have Movies.any_of(:Tags => /comedy/i) how can I get the value of _id? Movies.any_of(:Tags => /comedy/i).only(:_id) returns a document that I'm not able to get id from individually.. it just sets the other fields to nil.
Ended up using .only(:id) and saving that to a variable then going through it with .each and pushing it to an empty array

how do I get a list of uniq values with at least 2 occurrences?

I have this active record query:
current_user.company.properties.pluck(:name).uniq
what I would like to do is get this query but only for properties with 'name' that occur at least twice. how would i do that?
You can group by name and add a having call as well:
...properties.group(:name).having("count(name) > 1").pluck(:name)
There's no longer any need for the uniq call because, as you're grouping by name, you'll only get each name returned once.

Ruby on Rails 3: sort array based on data from ActiveRecord

I have one array, which are IDs from one ActiveRecord table.
so I would like to sort that array based on last name which is associated with that ID...how can I do that?
To clarify:
array #students=[], inside are IDs and I would like to sort by Student.find(ID).last
Thank you.
Dorijan
Without fully understanding the question, if you're given a list of id's, you can sort by last_name when you're doing the query:
Student.where("id IN (?)", #students).order(:last_name)
Of course, this assumes that #students is an array of ids and nothing else.
Responding to your comment, I'm not sure why you'd need to do that, but if your #student array is just a list of ids ignorant of the Student model and its attributes, and you would still like to order that array, you can do this:
#students = Student.where("id IN (?)", #students).order(:last_name).collect(&:id)
This will return an array of ids sorted by last name. But again, I don't really know what you have going on behind the scenes, and I'm not sure what you're asking for.
Based on your comment, you want to do the following:
Take in a list of IDs of students as input
Return a list of IDs ordered by the student's last name in the database.
You should be able to do the following:
Student.where(:id => #ids).order(:last_name).map(&:id)
Breaking this down:
where(:id => #ids) only selects Students with an ID in the ID array.
order(:last_name) sorts the results by last name.
map(&:id) takes in an array of Students and returns just the ID column. Essentially, the method in brackets (which is a shortcut for calling id for each student) is called for each student found, and the return values are assembled into a new array (which will only contain the ids).
Some gotchas:
If an ID doesn't exist in the database, it will be excluded from the results - if your result array is smaller than your input array, you may be trying to access a record that no longer exists.
If the Students table has a lot of columns, you may want to consider calling select(:id) so that you don't pull every column of the Student records from the database.
Student.find( #students ).sort_by { |s| s.last_name }

Identifying whether record/object is dirty in Rails

Is there anyway for me to identify whether an object/record is dirty before saving and which fields are changed in Rails?
Example
Suppose I have a Person model and Person has a property called name and age. In the db, Person with id 1 is named "John" with age 20.
p = Person.find 1
p.name #John
p.age #20
now, when I change his name from John to Nathan, is there any way for me to identify
the the object is changed (dirty)
and which fields got changed
Now I know the answer for the first one. If I change his name to Nathna, I can do the following
p.name = "Nathan"
p.changed? #true
However, is there anyway for me to identify which field was changed? May be a method that returns an array of fields that got changed?
p.dirty_fields #[:name]
See http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-changes, specifically changed.

Resources