0

I have this hash.

[#<PartnerSite id: 20, site_name: "test123", user_id: 178, 
               market_id: 164, created_at: "2014-01-15 18:02:01", 
               updated_at: "2014-01-15 18:02:01", 
               ip_address_range: "50.19.93.173", 
               public_key: "453df9eeeb4a2d85bb7ffeb85486d489">]

And I am trying to access value by using

partner_site[public_key]
partner_site.public_key

But it's showing error like

  1. undefined local variable or method 'public_key' And
  2. undefined method `public_key' Respectively.
3
  • Wait, what query is giving you undefined method 'site_name'? Don't you mean undefined method 'public_key'?
    – Ajedi32
    Jan 15, 2014 at 18:09
  • Isnt that an activerecord object?
    – beck03076
    Jan 15, 2014 at 18:10
  • @Ajedi32- Sorry ..... I mean 'public_key' Jan 15, 2014 at 18:18

2 Answers 2

2

First of all, that looks like an array containing one PartnerSite object, not a hash. So you'll want to either get the first object in the array with first, (E.g. partner_site = partner_site.first) or loop through all the elements in the array with each and do something to all of them.

Secondly, when using the [] form for accessing values you usually need to provide either a symbol or a string to the [] method. In partner_site[public_key], public_key references an undefined variable. Instead, you should do partner_site[:public_key] or partner_site["public_key"].

Your other form, partner_site.public_key doesn't work because either you're calling public_key on the Array and not the PartnerSite object (in which case see the first paragraph in this answer), or because PartnerSite doesn't have a #public_key method defined on it. In the second case, you can probably fix that by adding attr_accessor :public_key to the PartnerSite class.

0
1

You are calling to a variable that does't exist (public_key). Use a symbol instead:

partner_site[:public_key]

If you want to find out why symbols are used as hash keys, refer to this question

Your Answer

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

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