Populating and maintaining an instance array of arrays of hashes over multiple Ajax calls


#1

Hi,
I have a Currency model with id, name and exchange_rate attributes.
I have multiple select boxes for currencies in a form. These can be
added dynamically through JS too.
Im using an observe_field to make an Ajax call to the action
“currency_name” and retrieve the selected currency from the database
using the id.

Following this Ajax call, currency_name.rjs is rendered where i update
the “selected_currencies” div with the currency name and amount(which
is the exchange_rate * some_value). In case a previously chosen
currency is chosen again, only the amount should get updated. But if a
new currency is chosen, “selected_currencies” should get appended with
the new currency’s name and amount.

To accomplish this condition checking, I thought of having an instance
@selected_taxes which is an array of arrays (like
[[“currency1_id”,“currency1_name”,“currency1_rate”],
[“currency2_id”,“currency2_name”,“currency2_rate”] , …] ) OR an
array of arrays of hashes (which carry the appropriate keys for the
values). But this array seems to refresh on every Ajax call. I’ve
paste the controller code below

def currency_name
@chosen_currencies ||= []
flag = 0
@currency = Currency.find(params[:currency_id])
@chosen_currencies.each do |id|
if (@currency.id == id)
flag = 1
end
end
@chosen_currencies << @currency.id unless (flag == 1)
raise @chosen_currencies.to_yaml
end

This results in the instance having only one ID at a time.
Firstly, is my approach correct? Or is there a better way?
And secondly, if my approach is correct, how can i maintain this
instance over multiple Ajax calls?
Hope someone can help me out with this.