8

tl;dr How do I get the corresponding value with the key of an object?

I'm confused why

Atag.where(tag:'brand') gives me what I would call an object for lack of a better term: #<ActiveRecord::Relation [#<Atag id: 1, tag: "brand", created_at: "2015-01-31 04:29:20", updated_at: "2015-01-31 04:29:20">]>

But I'm having the basic difficult of accessing the corresponding value for the key :id.

Atag.where(tag:'brand').id and Atag.where(tag:'brand')[:id] and Atag.where(tag:'brand')(:id) all throw errors, while in this case I'm just trying to have the integer 1 returned.

I seem to be unable to ruby, nor find a succinct answer to this basic question with my google searching skills (or lack there of).

Thanks

2
  • ah did Atag.where(tag:'brand')[0].id and that worked
    – Laser
    Jan 31, 2015 at 5:02
  • I see the 'where' method returned an object of objects, so I needed to specify I wanted the first object.
    – Laser
    Jan 31, 2015 at 5:03

4 Answers 4

7

From great documentation at the Odin Project.

The key thing to note is that #find returns the actual record while #where returns an ActiveRecord::Relation which basically acts like an array.

So if you're using #where to find a single record, you still need to remember to go into that "array" and grab the first record, e.g. User.where(:email => "[email protected]")[0] or User.where(:email => "[email protected]").first.

This gets me all the time...

1
  • I'd like to add: it's possible to chain .id onto things. So for @Laser original question, a possible solution would be: Atag.select(:id).limit(1).first.id What this is doing is collecting the ActiveRecord::Relation object (which is essentially an Array) looking at the first element, and specifically the id of the first element. This way it's not necessary to ever know the actual id before referencing it. Nov 13, 2022 at 15:50
6

Get the id of your tag = 'brand' with following query:

Atag.find_by(tag:'brand').id 

Check following variations:

Atag.find(1) 
#gives you the object with the Atag id = 1

Atag.find(100) #let's say this record does not exist then you will 
get ActiveRecord::RecordNotFound exception. 

Better option :

Atag.where(id: 1) 
#this returns you a relation and it's true you are trying to access
 only a single object.

Hence, you just need to modify it to :
Atag.where(id: 1).first 
#Above one will give you an object of Atag not an association result.
# to verfiy you can execute, Atag.where(id: 1).first.class

Atag.where(id: 999).first
 # In this case if there is no record found with id = 999, then it'll 
return  nil which can be easily handled than an exception found 
while using find method.

Get the same flavor using the dynamic finders.

Atag.find_by(id: 1) #gives the Atag with id 1 
Atag.find_by_id(1). # same as above.
Atag.find_by(id: 999) #if not found then simply returns nil. 
Atag.find_by(name: 'ruby') #return Atag object with name: 'ruby'
Atag.find_by_name('ruby') #same as above. 
6
  • This is useful, but a different from what I was looking for, as I needed to be able to retrieve the value with knowledge only of the key. Your examples seem to assume knowledge of the key and value to retrieve the object. The reason I am retrieving the objects by :tag instead of :id is because I have the value of :tag but not the :id (which is what I am trying to get). There is almost definitely a better way to implement what I'm trying to with Active Record Associations, but I'm just working on a implementation from scratch for now while I get more comfortable and inspired by making progress.
    – Laser
    Jan 31, 2015 at 5:44
  • I'm not big on reading docs, except the bare minimum, but at some point in the near future I'll thoroughly go through guides.rubyonrails.org/association_basics.html if I get too stuck :P
    – Laser
    Jan 31, 2015 at 5:45
  • 1
    @Laser, are you trying to get all the Atag objects having a common tag name ? Just like you did Atag.where(tag: 'brand') ? then you can try Atag.find_by(tag: 'brand')
    – Ajay
    Jan 31, 2015 at 5:50
  • Ah yes that's much cleaner! Thanks :)
    – Laser
    Jan 31, 2015 at 5:54
  • Can you edit the answer so that the solution is at the top 'Atag.find_by(tag:'brand').id' or 'Atag.where(tag:'brand').first.id'?
    – Laser
    Jan 31, 2015 at 6:04
1

Yep, looks like you figured it out. For reference, you can use Atag.where(tag:'brand').first to get the first result, and Atag.where(tag:'brand').to_a to get an array of all the matching results.

1

where return instance of ActiveRecord::Relation which can be treated like an array with records as its members. Even if the result is single it should be accessed like a member of array with single element

Atag.where(tag: 'brand')

returns the array of results and to access id we should get the record from the array first i.e.

Atag.where(tag: 'brand')[0].id

In order to get id of all the matching records we need to use pluck with where. pluck returns an array of attribute that is plucked.

Atag.where(tag: 'brand').pluck(:id)

This would return an array of id from the collection returned by where only.

The find_by method finds the first record matching some conditions. Since find_by returns the record (not an array) , we can do:

Atag.find_by(tag: 'brand').id

PS: No one had mentioned pluck that's why I wrote this answer. Hope its helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.