Reputation: 67
I'm new to rails and I want my controller to update label/html field in view with the variable @msg created from an action. right now I have,
View form:
<%= form_tag({controller: "home", action: "drawMoney"}) do %>
<h1> Draw Out </h1>
<%= number_field_tag :draw, min: 1, max:1000 %>
<%= date_field_tag :customDate %>
<%= submit_tag "Save" %>
<% end %>
<p>
<%= "#{@msg}" %>
</p>
Controller
def drawMoney
@drawAmount = params[:draw]
@credit = Credit.getCredit('1')
@updateAmount = updatePrincipal(@credit.principal, @drawAmount)
@newLimit = updateLimit(@credit.currLimit, @drawAmount)
@msg = "success!"
if (@transaction = Transaction.create(userId: @credit.userId, date: params[:customDate], OPB: @credit.principal, amount: @drawAmount).valid?)
@credit.update(principal: @updateAmount, currLimit: @newLimit)
@transaction = Transaction.create(userId: @credit.userId, date: params[:customDate], OPB: @credit.principal, amount: @drawAmount)
else
@msg = "not valid"
end
redirect_to action: "index"
end
I've read ruby docs and youtube tutorial, tried putting @msg in the view instead and @msg in html etc.. but this is not printing anything to the view, and couldn't really find answers from search. Any help would be appreciated!
EDIT:
I tried changing to <%= @msg %> but it doesn't work.. so the method is called when I click the submit button, and until then there is no @msg instance. Could that be a problem?
Upvotes: 1
Views: 1444
Reputation: 5861
when you redirect to index, your currently defined variables will be cleared.
controller
flash[:msg] = "Success"
redirect_to action: "index"
view
<% if flash[:msg] %>
<div class="message"><%= flash[:msg] %></div>
<% end %>
Upvotes: 3
Reputation: 1580
Change this <%= "#{@msg}" %>
to <%= @msg %>
You don't have to interpolate here, rails view have direct access to controller instances when you create it with a @ sign.
Upvotes: 0