1

I am learning rails and have run into bump.

I have a view that contains the following:

<span><%= @goals.cost_per_conversion %></span>

(just as an example while @goals actually contains more then just cost_per_conversion)

Under certain circumstances the view will not have the instance variable @goals. I am trying to guard against cases when this is true.

In my controller I have the following code:

if Goal.exists?(params[:id])
   @goals = Goal.find(params[:id])
else
   @goals.cost_per_conversion = 'N/A'
end

Naturally this returns an error as .conversions is not a method.

How do I set the conversions param so that my view can still work when there is no @goals variable available.

3 Answers 3

3

Use #try :

<span><%= @goals.try(:cost_per_conversion) %></span>

And change the controller code :

@goals = Goal.find(params[:id])

Double checking record in controller is expensive. Btw, since it's a single record, you could name it @goal instead of @goals.

Sign up to request clarification or add additional context in comments.

1 Comment

in this case however @goals is not a single record. but your previous answer was perfect and this applies as well! Thanks
1

you can use if:

<% if @goals %>
    <span><%= @goals.cost_per_conversion %></span>
<% end %>

and change the controller code to:

if Goal.exists?(params[:id])
   @goals = Goal.find(params[:id])
end

or

if params[:id]
   @goals = Goal.find(params[:id])
end

Comments

0

You might consider creating a new Goal object with @goals = Goal.new in case the goal could not be found in the database. Or you could make a null object that acts like a goal, following the null object pattern.

These are just two ways to approach it, and are not necessarily better than the other answers.

By the way, since your instance variable just contains one goal and not a collection of goals, it should be named @goal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.