I am a student and I got the memo (without explanation) that my following code is bugged and can be much better. How would you improve my controller#newname
method? Thank you for your time!
class ReviewController < ApplicationController
def index
@reviews = Review.all.order(created_at: :desc)
end
def newname
@review = Review.find(params[:id])
if @review.update_attribute(:title, sanitize(params[:title]))
format.json { render json: { status: 200 } }
else
format.json { render json: { status: 500 } }
end
end
end
The biggest flaw is that update_attribute
skips all the validations, hence, your else statement will rarely/never be executed. Change it to:
@review.name = sanitize(params[:title])
if @review.save
#...
and it should be much better.
I think you could perhaps do something similar to:
class ReviewController < ApplicationController
def index
@reviews = Review.all.order(created_at: :desc)
end
def newname
@review = Review.find(params[:id])
if @review.update(:title => sanitize(params[:title]))
render json: @review
else
render :json => { errors: @review.errors.full_messages }, status: 422
end
end
end
The idea being to stay 'on the rails' and let the conventions do the work for you.
This addresses the
To build upon BroiSatse's answer, I would definitely use save instead of update_attribute. I would also return the errors that occur so the user can parse or show them. If you're on Rails 4, use strong params (declare in a private method in controller)
def newname
@review = Review.find(params[:id])
@review.title = sanitize(params[:title])
if @review.save
format.json { render json: { status: 200 } }
else
render :json => {:errors => @review.errors.full_messages}, :status => 422
end
end
class ReviewController < ApplicationController
before_action :set_review, only [:newname] #list additional methods as needed...
...
def newname
#@review is retrieved from set_review
if @review.update(review_params)
format.json { render json: { status: 200 } }
else
render :json => {:errors => @review.errors.full_messages}, :status => 422
end
end
private
def set_review
@review = Review.find(params[:id])
end
def review_params
params.require(:review).permit(:title)
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.