I have an issue storing the result of a query in a controller:
payments = Payment.select("SecurityKey").where("VendorTxCode = '%#{params[:VendorTxCode]}%'").limit(1)
payments.each do |payment|
security_key = payment.SecurityKey
end
Later when I use security_key
, I get an error that it is undefined. However, when I run this in the rails console
as:
payments.each do |payment|
puts payment.SecurityKey
end
#=> df4g5ds6
How can I store this result in a variable for use later on as my method is not working?
It looks like you need to define your variable before your each do block. Try storing the keys into an array as such:
payments = Payment.select("SecurityKey").where("VendorTxCode = '%#
{params[:VendorTxCode]}%'").limit(1)
security_key = []
payments.each do |payment|
security_key << payment.SecurityKey
end
And then you can access the keys like security_key[0], etc.