Rails Associations -
i have 2 tables, movies , likes. movie has_many :likes, dependent: :destroy, foreign_key: "movie_id"
, belongs_to :movie
in likes controller there 2 actions: uplikes (where :vote=>1)
, dislikes (where :vote=>2)
in movies/show.html.erb
show amount of uplikes , dislikes movie has such :
- view show.html.erb
<%= @uplikes.size %>
<%= @dislikes.size %>
- controller
def show
@uplikes = like.where(:movie_id => params[:id], :vote => '1')
@dislikes = like.where(:movie_id => params[:id], :vote => '2')
this works fine. have problems displaying amount of dislikes , uplikes of movie in index action when calling movies.each
i have pasted above controller code def show
action def index
action , changed params[:id]
params[:movie_id]
but when call
<%= @uplikes.size %>
<%= @dislikes.size %>
to view, displays 0
if rid of :movie_id => params[:id],
in controller, shows number of uplikes , dislikes movies, not specific one.
anyone have answer this?
thanks
in index iterating on (or perhaps subset due pagination) movies, correct? naive implementation
in controller
def index @movies = movie.all end
in index.html.erb
<% @movies.each | movie | uplikes = movie.likes.where(vote: 1).count dislikes = movie.likes.where(vote: 2).count %> ... output logic here ... <% end %>
or following
in movie.rb
has_many :uplikes, -> {where vote: 1 }, class_name: 'like' has_many :dislikes, -> {where vote: 2}, class_name: 'like'
then can use movie.uplikes.count
or movie.dislikes.count
in views.
Comments
Post a Comment