I'm missing something very simple, just not sure what. I have two actions in the same controller AppProxy. One action, AppProxy#return_credit is used to POST data too via AJAX, and it works great:
def return_credit
customer = Customer.find_by(email: params["email"])
@credit_amount = customer.credit_amount.to_f
render json: @credit_amount, :status => :ok
end
The above action works great, and returns @credit_amount just fine. However, when I need to use @credit_amount in another action within the same controller, AppProxy#credit that feeds a view, @credit_amount has disappeared and is now empty.
def credit
@credit_amount
# if I do puts "#{@credit_amount}" here its empty,
# and obviously same in view
end
I've also tried putting attr_reader :credit_amount in this controller, but it doesn't help.
How can I use the @credit_amount variable in my credit action?
As credit action located in the different controller, you can not share variables between two controllers in such manner. For this purpose, there is Model.
Update:
You have updated question, and answer the same, you can not share variables between two actions(requests) in such manner. You can move logic to separate method
def set_credit_amount
customer = Customer.find_by(email: params["email"])
@credit_amount = customer.credit_amount.to_f
end
and use this method in before_action or call directly in actions, however, you can not save the variable(data) in one action(request) and then use it in another.
If you want to share data between two actions(requests), you need to store it somewhere., in sessions or in NoSQL Database like Redis.
@credit_amount needs to be set again.
If you were to use this again:
customer = Customer.find_by(email: params["email"])
@credit_amount = customer.credit_amount.to_f
Then @credit_amount would have the same value as in #return_credit. If this is the value you would want then I would recommend making a private method which all of your actions can access.