问题
I have a @shows Controller where every user can create a Show (Singular).
On the Show Creation View (shows/new) i want to display a counter of how many shows there are already.
i tried:
def count
@shows.all.count
end
# in my Shows Controller
and then called <%= @count %>
on my view. But i guess this isn't the right way.
I tried calling it directly on my View:
<%= @shows.count %>
but neither this worked.
Can someone help me out ?
回答1:
@show_count = Show.count
will do your job.
In your view <%= @show_count%>
回答2:
You need to create the @count variable in your new
method in the controller or use a helper method from your view
controller version
def new
# your other code here
@count = Shows.count
# @count is now available in your view for `new`
end
You could always simply call <%= @shows.count %>
inside your view.
Yes, you should only do minimal code stuff in your view but this is just a simple call, not a method chain doing complex things, so it's alright to do that.
With the code given, I cannot say why @shows.count
didn't work for you in the view. Maybe you forgot to add the .all
in your controller?
来源:https://stackoverflow.com/questions/18764418/how-to-count-user-inputs-from-a-controller