Search code examples
ruby-on-railsrubyruby-on-rails-4hashnomethoderror

Dynanmically update specific rails attributes


I have a constant hash P_FACT_MAP and an array of keys of the previous hash product_params[:product_factors]. In P_FACT_MAP all values are mapped to another value or an array of values which are the attribute names of the ProductFactor table.

P_FACT_MAP = {
  :x => %w[something]
  :y => %w[something2, something]
  :z => %w[something 3, something1]
  ...
  ...
}

I'm trying to update the dynamic attribute values by doing:

ProductFactor.v << product_params[:p_id]

The complete method code:

ProductFactor::P_FACT_MAP.collect.do |k, v|
  puts "Value #{v}"
  if product_params[:product_factors].include? k
     v.each do |f|
       @coach_recommendation_factor.send(f) << @coach.id
   end
end

But it doesn't recognize the attribute name v and I get the following error:

NoMethodError (undefined method `v' for #<Class:0x007f95de9b8180>)

Is it not possible to update the value of an attribute dynamically or do I have to take a completely different approach to reach that?


Solution

  • 'v' is not a method for your ProductFactor class. If you are trying to use the variable v from |k, v| then replace ProductFactor.v with ProductFactor.send(v)