1

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?

1
  • It's because you're redirecting. It loses all of your set variables. Use the flash as @imechemi suggests Commented Dec 4, 2015 at 17:03

3 Answers 3

3

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 %>
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

<pre>
  <%= @msg %>
</pre>

Comments

0

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.

2 Comments

Thanks for the input! :)
@imechemi is correct, important point. when you redirect to index, variables in index is now accessible in the view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.