Arvid Boome
Arvid Boome

Reputation: 49

Inserting and editing user reviews

I have a review system which lets users create reviews for films, and, if they try to add another review for the same film it updates their previous one. The update is done through the create method in the review controller.

I'm trying to use this in films show page. Currently users can add a review by choosing the "add review" option on the show page of a film which is always there. If they have written a review for that particular film before by choosing 'add review' their previous review is still updated. What I want to do is to display a button saying "edit review" if they have written a review before and "add review" if they haven't. Any ideas?

review controller - create:

def create    
@review = Review.find_or_create_by_film_id_and_name(params[:review][:film_id],        
User.find(session[:user_id]).name)
@review.update_attributes(params[:review])
if @review.save
film = Film.find(@review.film.id)
redirect_to film, notice: 'Your review was successfully added.'
else
render action: "new"
end
end 

review controller - new:

def new
if logged_in?
@review = Review.new(:film_id => params[:id], :name =>     
User.find(session[:user_id]).name)
session[:return_to] = nil 
else
session[:return_to] = request.url 
redirect_to login_path, alert: " 'You need to login to write a review' "
end
end

film show page:

<%= button_to 'Add Review',{controller: 'reviews', action: 'new', id: @film.id },
{class: "button-to"}%>

Upvotes: 0

Views: 168

Answers (2)

Ramya
Ramya

Reputation: 117

<% if @current_user_review.blank?%>
   <%= link_to_function("Create New Review", "$('create').toggle()") %>
<%else%>
   <%= link_to_function("To edit Review, Click here", "$('Edit').toggle()") %>
<div id="create" style="display: none;">
   <%= render :partial => "new" %> 
</div>

<div id="Edit" style="display: none;">
   <%=render :partial => edit %> # The new partial can also be be used here.
</div>

Upvotes: 0

Rahul Tapali
Rahul Tapali

Reputation: 10137

You can do something like below:

In show action of controller:

 def show
   @current_user_review = Review.find_by_film_id_and_name(film_id, user_name)
   #your stuff
 end

 def edit
   @review = Review.find(params[:id])
   render 'new'
 end

In view:

 <% if @current_user_review.blank? %>
   <%= link_to 'Add Review',new_review_path(film_id: @film.id),
      {class: "button-to"}  %>
 <% else %>
   <%= link_to 'Edit Your Review', edit_review_path(@current_user_review), {class: "button-to"} %>
 <% end %>

Upvotes: 2

Related Questions