How to “count” user inputs from a Controller

旧城冷巷雨未停 提交于 2019-12-13 02:38:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!