BalajiB BalajiB - 7 months ago 11
Ruby Question

Dynamically change the column name of the database and store values into it in ruby on rails

In my view page, i have hash of data in the format

"round"=>{"1"=>"a", "2"=>"b", "3"=>"c", "4"=>"d"}


and i have four columns
round1,round2,round3 and round4


Now dynamically im storing these hash values into the these 4 columns

im following the following way

if params[:round].present?
count=1
params[:round].each do |k,v|
@data.("round"+"#{count}")=v
count+=1
end
end


here
@data=MgData.new()


in the above code, i want to save it as
@data.round1=v,@data.round2=v....
but im ending up with error

Answer

I believe your this line : @data.("round"+"#{count}")=v is causing the error

This is how you should be assigning attributes dynamically

if params[:round].present?
  params[:round].each do |k,v|
    @data.send("round#{k}=", v)
  end
end
Comments