I'm trying to add a very simple rating system to a little app. I have a movies model and a ratings model. A rating belongs_to a movie and a movie has_many ratings. I want a simple funcionality of having 5 buttons with stars, each button should create a new rating for a specific movie with the coresponding value (1-5)
I have them in a button group like so:
<div >
<%= button_to "*",{:controller => "ratings", :action => "create", :movie_id => @movie.id, :value => 1} , :method=>:post, class:"btn btn-outline-warning" %>
<%= button_to "*",{:controller => "ratings", :action => "create", :movie_id => @movie.id, :value => 2} , :method=>:post, class:"btn btn-outline-warning" %>
<%= button_to "*",{:controller => "ratings", :action => "create", :movie_id => @movie.id, :value => 3} , :method=>:post, class:"btn btn-outline-warning" %>
<%= button_to "*",{:controller => "ratings", :action => "create", :movie_id => @movie.id, :value => 4} , :method=>:post, class:"btn btn-outline-warning" %>
<%= button_to "*",{:controller => "ratings", :action => "create", :movie_id => @movie.id, :value => 5} , :method=>:post, class:"btn btn-outline-warning" %>
</div>
which is not droping any errors, so i assumed it works, and proceeded to try and add an "Average rating" section to my _movie partial, which renders in the show view.
I tried this:
<p>
<strong>Hodnocení:</strong>
<%= movie.ratings.average(:value) %>
</p>
and it remains blank.
My ratings_cotroller.rb:
class RatingsController < ApplicationController
before_action :find_movie
def new
@rating = Rating.new
end
def create
@rating = Rating.new(rating_params)
@rating.movie_id = @movie.id
end
private
def rating_params
params.permit(:value)
end
def find_movie
@movie = Movie.find(params[:movie_id])
end
end
Any ideas as to why it's blank? Is some part of my code wrong or am I missing something?
CodePudding user response:
I think you forget to save it.
def create
@rating = Rating.new(rating_params)
@rating.movie_id = @movie.id
@rating.save
end
CodePudding user response:
As far everything thing looks good but you can create an instance of your review model which means it is temporary and is stored on ram and as you leave the controller the Garbage collector will collect it and delete it from memory and you will lose your progress!
Review.new will do nothing on database.
What you can do is Review.create(your data) or review = Review.new(your data) then processing that you want if any and than review.save
Save() method when called, hits the database and stores the instance in db while Create() method directly hits to the databases and you don't have to call save method to save data in db. Thats it.
