Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Ruby Standard Library ERB

Shunji Lin
Shunji Lin
12,896 Points

Displaying Balance in Template

So I am trying to display the balance amount within the TEMPLATE, by adding this to the variable TEMPLATE, like so:

You have a balance of: <% balance = @transactions.inject { |sum,iteration| sum+=iteration} %><%= balance%> /p>

Just want to ask if this is the best way to do it, the idea of a variable (balance) within a variable (TEMPLATE) is a little confusing for me!

1 Answer

Lin,

Since no one is answering this I will give it a try. Hopefully this helps.

I don't think its a good idea to have logic in your views. I would write a method. Its hard for me to tell you where to put the method without seeing all of your code, but I would probably write it as a helper method (perhaps on the TransactionsController?).

You could write your method like this:

def balance(transactions)
  transactions.inject { |sum, iteration| sum += iteration }
end

And then you could call your method in the view by passing it the array you placed into an instance variable, if you really want to:

<%= balance(@transactions) %>

I think this might work.

Nathan

Jason Goebel
Jason Goebel
4,351 Points

Yes, this works. I did something close, however, it did not work because I didn't understand how to call methods from within a template util I saw your code. Now I know... <%=

Thanks Nathan.

Shunji Lin
Shunji Lin
12,896 Points

Hi Nathan, Jason

Thank you very much and sorry for the late reply! Yes that definitely makes much more sense!