j-dexx
j-dexx

Reputation: 10406

Inject on ActiveRecord objects

I'm trying to create a hash based on an ActiveRecord query in a model quit_reasons the return from a has_many associations

reasons = quit_reasons.inject({}) do |result, element|
  result[element.name] = element.id
end

I keep getting

undefined method `[]=' for 2:Fixnum

and I have no idea why

Upvotes: 1

Views: 3877

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118271

Fix is :-

reasons = quit_reasons.inject({}) do |result, element|
  result[element.name] = element.id
  result
end

The reason is, Hash#[]=, returns the value is being assigned to the key. As this method Hash#[]= is your block's last statement, return value of #[]= is being assigned to the result, which is causing the error for the next Hash#[]= call.

I always try to use thus #each_with_object if I can. Though the object is passed as the first parameter and the result as the second (i.e. the opposite way around to inject)

reasons = quit_reasons.each_with_object({}) do |element, result|
  result[element.name] = element.id
end

This one of the most important difference between #inject and #each_with_object.

Upvotes: 4

spickermann
spickermann

Reputation: 106882

The block needs to return the result. What can be achieved by using merge or update on the hash:

reasons = quit_reasons.inject({}) do |result, element|
  result.update(element.name => element.id)
end

Upvotes: 0

j-dexx
j-dexx

Reputation: 10406

Damn I'm an idiot.

I forgot to return the result

reasons = quit_reasons.inject({}) do |result, element|
  result[element.name] = element.id
  result
end

Upvotes: 0

Related Questions