'Rails ERB Validation
I'm trying to add a validation to my Rails app in order to display an error message if the user goes to the wrong id. The project has reviews, if I go to http://localhost:3000/reviews/:id that doesn't exist
the app crashes, I'd like to prevent the runtime error by displaying a message.
In the model, I got this validation:
class Review < ApplicationRecord
validates :id, presence: true
end
Then, in the reviews/show.html.erb
file, I'm trying this:
<% if @review.valid? %>
<div class='review-header'>
....
</div>
<% else %>
<% @review.errors.objects.first.full_message %>
<% end %>
This is also the Reviews Controller:
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
before_action :authorize!, only: [:edit, :destroy]
def index
if params[:search]
@reviews = Review.where("title like ?", "%#{params[:search]}%")
else
@reviews = Review.all
end
end
def new
@review = Review.new
@comment = Comment.new
@comment.review_id = @review.id
#We need to declare the comments in the new action.
end
def create
@review = current_user.reviews.new(review_params)
if @review.save
redirect_to review_path(@review)
else
render 'new'
end
end
def show
@comment = Comment.new
#We also need to declare the new comment in the show action.
end
def edit
end
def update
if @review.update(review_params)
redirect_to review_path(@review)
else
render 'edit'
end
end
def destroy
@review.destroy
redirect_to reviews_path
end
private
def set_review
@review = Review.find_by(id: params[:id])
end
def review_params
params.require(:review).permit(:title, :content, :category_id, :search)
end
def authorize!
authorize @review #authorize method using the Pundit gem
end
end
However, my project keep crashing rather than showing a message. If there's any way I can make this work? Thanks.
Solution 1:[1]
The problem is that if the ID does not correspond to a review in the database, the @review
object will be nil
, and your line if @review.valid?
will throw an error.
You need a different test, something like
<% if @review.present? %>
<div class='review-header'>
....
</div>
<% else %>
Review does not exist.
<% end %>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | eugen |