The action bellow creates a new comment.
- A user has many statuses
- A status has many comments
How can optimize this action so that head 401 and return is not repeated many times.
def create
@user = User.where(id: params[:user_id]).first
if @user
if current_user.friend_with?(@user) or current_user == @user
@status = @user.statuses.where(id: params[:status_id]).first
if @status
@comment = @status.comments.build(params[:comment])
@comment.owner = current_user
if @comment.valid?
@comment.save
current_user.create_activity(:comment_status, @comment, @user)
else
head 401 and return
end
else
head 401 and return
end
else
head 401 and return
end
else
head 401 and return
end
end
Thank you.
When do you want to return
401?Instead of using so many conditionals, you can use methods that raise exceptions. When you do so, you can rescue from that exceptions with the desired behavior (rendering
401).So my suggestions for listed conditions are:
find!instead ofwhereand thenfirst.raisesomething, preferably custom exception (NotAFriendError)find!create!, it’s an equivalent tonewand thensave!which will raiseActiveRecord::RecordInvalidexception if it fails on validation.Here’s the result: