Good morning,
In my Ruby On Rails application I am trying to build a stat counter for wins and for losses.
These stats are displayed in the sidebar of my page, which is always visible. For these values i use a model named Stats. The stats should be available global, since I want to display them on every side so they were put into application_helper.rb. I also have two actions, that should be called if you click on the add win / or add loss link, which is only displayed for admins. After clicking the link you get redirected to the main page. At the moment, both counters increase each time someone enters the site or refreshes it. Can you please help me, I am looking to solve this problem now for several hours and i still don’t get it.
My application_helper
module ApplicationHelper
def stats
@stats = Stats.find(1)
end
def addwin
@stats = Stats.find(1)
@stats.update_attribute(:wins, @stats.wins+1)
end
def addloss
@stats = Stats.find(1)
@stats.update_attribute(:loss, @stats.loss+1)
end
end
An extract of my application.html.erb file, where the sidebar is located:
<tr><td>Dotards StatsTracker</td></tr>
<tr><td>Wins: </td><td style="color:green"><%= stats.wins%></td></tr>
<tr><td>Losses: </td><td style="color:red"><%= stats.loss%></td></tr>
<hr>
</table >
<%if user_signed_in? && current_user.admin? %>
<small><%= link_to "Add Win", news_index_path(addwin) %>|<%= link_to "Add Loss", news_index_path(addloss)%></small>
<% end %>
Would be awesome if someone could help me, because I don’t know what else i can do.
Thank you very much in advance.
calls the add win method directly on generation of the page, that’s why the counter is increased.
move the two methods to an appropriate controller (maybe news_controller?) and create routes in config/routes.rb like this:
then you get path helpers which you can use like this:
run
rake routesto see the helper names generated.addition: I would also consider your Singleton Stat into a model, and define methods there which are just used by the controller.