Fix error: NoMethodError (MAYBE-MARKETING-8) #160
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The error
NoMethodError: undefined method 'symbol' for nil:NilClass
occurs when we try to call thesymbol
method on anil
object. In this case, it's happening because the@stock
variable isnil
, which means theStock.find_by(symbol: params[:ticker])
query didn't find a matching stock.To fix this, we need to use the
find_by!
method instead offind_by
. The bang version (find_by!
) will raise anActiveRecord::RecordNotFound
exception if no record is found, rather than returningnil
. This is preferable because:NoMethodError
from occurring further down in the view.Here's a detailed explanation of the change:
find_by
withfind_by!
in theshow
action of theStocksController
.ActiveRecord::RecordNotFound
exception if no stock is found with the given ticker symbol.symbol
on anil
object.This change maintains the original intent of the code (finding a stock by its ticker symbol) while adding a layer of error handling that improves the user experience and application robustness.
Tip
You can make revisions or ask questions of Revise.dev by using
/revise
in any comment or review!/revise Add a comment above the method to explain why we're making this change.
/revise Why did you choose to make this change specifically?