Reputation: 231
I have two tables, Movies and Likes.
A movie has_many :likes, dependent: :destroy, foreign_key: "movie_id"
and a like belongs_to :movie
In the Likes controller
there are two actions: uplikes (where :vote=>1)
and dislikes (where :vote=>2)
In the movies/show.html.erb
I show the amount of uplikes and dislikes the movie has
As such :
<%= @uplikes.size %>
<%= @dislikes.size %>
def show
@uplikes = Like.where(:movie_id => params[:id], :vote => '1')
@dislikes = Like.where(:movie_id => params[:id], :vote => '2')
THis works fine. Now what i have problems with is displaying the amount of dislikes and uplikes of a movie in the Index action when calling movies.each
I have pasted the above controller code from the def show
action to the def index
action and changed params[:id]
to params[:movie_id]
But when i call
<%= @uplikes.size %>
<%= @dislikes.size %>
to the view, it just displays 0
If i get rid of :movie_id => params[:id],
in the controller, it then shows the number of ALL the uplikes and dislikes for all movies, not that specific one.
Anyone have an answer to this?
Thanks
Upvotes: 1
Views: 143
Reputation: 20232
in the index you are iterating over all (or perhaps a subset due to pagination) movies, correct? A naive implementation would be
in the controller
def index
@movies = Movie.all
end
in index.html.erb
<% @movies.each do | movie |
uplikes = movie.likes.where(vote: 1).count
dislikes = movie.likes.where(vote: 2).count
%>
... output logic here ...
<% end %>
Or you could do the following
in your movie.rb
has_many :uplikes, -> {where vote: 1 }, class_name: 'Like'
has_many :dislikes, -> {where vote: 2}, class_name: 'Like'
then you can just use movie.uplikes.count
or movie.dislikes.count
in your views.
Upvotes: 3