How to extract value from hash in Rails

3.3k views Asked by At

I have a Hash and need to use the value year from a variable in it The example is:

2.2.4 :001 > @values_project
=> [#<CustomValue id: 20367, customized_type: "Project", customized_id: 492, custom_field_id: 64, year: "2017">] 

and I need the year so when I try @value_hash.year receive the error

NoMethodError: undefined method `year' for
#<ActiveRecord::Relation:0x0000000712fb18>

I don't understand why

4

There are 4 answers

0
jvillian On BEST ANSWER

@value_hash is not a hash, it's an ActiveRecord::Relation (as the error states).

In your example, @value_hash has only one member. To get that member, which is an instance of the class CustomValue (which is still not a hash!), you can do:

custom_value = @value_hash.first

Then, to get the year, you can do:

custom_value.year

Or, you could do it in one shot as:

@value_hash.first.year

Which is just a long way of saying exactly what Sachin R said (so you should accept their answer).

0
Becki Srofe On

If you are trying to get the value for the key year and your hash is @values_project then you would use
@values_project[:year]

1
Sachin R On

since it is array of objects use like that

@values_project.each do |value_project|
  value_project.year
end

or

@values_project.first.year
0
army_coding On

You can try the following ways as well :

@value_project[0].year