j-dexx j-dexx - 1 year ago 99
Ruby Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download