Topic: SOLVED how to pass a variable value to an attribute name

here is a simplified version of my (incorrect) code to explain what I am trying to do:

                 nutrientdefinitions = NutrientDefinition.find (:all)
                 @ingredient = Ingredient.new
                 nutrientdefinitions.each do |nutrientdefinition|
             nutrient_name = nutrientdefinition.Tagname
                     # this is the incorrect line that gets rejected :
                 @ingredient.#{nutrient_name} = 12                   
                 end

The table Ingredients has a large number of columns, each column corresponds to a given nutrient type. The list of possible nutrients are stored in the NutrientDefinitions table.
I am trying to loop over the nutrient list, to assign a value (let's say "12" in this example) to each column of the ingredients table.
I need to pass the value of the variable nutrient_name to the attribute name of ingredient.
I don't know how to do that.

Thanks

Last edited by carrot06 (2012-04-08 16:28:33)

Re: SOLVED how to pass a variable value to an attribute name

Hmmm... are you able to post more code? I think with more code to see how you currently have things setup we could help.

Re: SOLVED how to pass a variable value to an attribute name

here is my complete code:

class PopulateIngredients < ActiveRecord::Migration
 
  def self.up
 
    fooditems = FoodItem.find (:all)
    nutrientdefinitions = NutrientDefinition.find (:all)
   
    fooditems.each do |fooditem|
            @ingredient = Ingredient.new
           @ingredient.id = fooditem.food_id
           @ingredient.name = fooditem.name
          
           nutrientdefinitions.each do |nutrientdefinition|
             nutrient_name = nutrientdefinition.name
             nutrient_id = nutrientdefinition.nutrient_id
             if nutrient_name != ""
             nutrientdata = NutrientData.find (:first,
                                                    :conditions => ["nutrient_id= ? and food_id = ?",nutrient_id, fooditem.food_id])
             @ingredient.#{nutrient_name} = nutrientdata.value
             end
           end
           
           @ingredient.save
    end
 
  end

  def self.down
  end
 
end

Re: SOLVED how to pass a variable value to an attribute name

Change your line:

#FROM THIS
@ingredient.#{nutrient_name} = nutrientdata.value

#TO THIS
@ingredient.send("#{nutrient_name}=", nutrientdata.value)

Use the "send" method to call a method by a string. Google and do research on Ruby's "send" method (also called __send__).

Hopefully that's what you're looking for smile

Remember to edit your topic title and add "[SOLVED]" if your question has been answered!

Follow me!

Re: SOLVED how to pass a variable value to an attribute name

Yes it worked. Thanks