1

Is there a way to write a clean if nil then in a view. Assuming my lack of ruby is biting me here. Example,

If object nil, then return, nothing found

have

<%= @objects.count if @objects %>

want something like this

<%= @objects.count if @objects then "nothing found" %>

2 Answers 2

2

There are many ways to write something like this.

Something simple would be:

<% if @objects %>
  <%= @objects.count %>
<% else %>
  nothing found
<% end %>

If you get into a slightly more complex conditional I would suggest moving the logic into a helper and call it from the view. ex:

<%= count_for(@object) %>
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a good solution for you:

<%= "nothing found" unless @objects.try(:length).to_i > 0 %>

One of the issues is that you can't run count on a nil object. Therefore you need to use Rails' super handy .try() method to return nil when @objects = nil, rather than NoMethodError.

Next issue: You can't make a comparison between nil and a number using > so you need to convert the results of @objects.length to an integer which will return 0 for nil.

Lastly, try calling length rather than count. This will avoid running any extra queries when @objects is defined.

Avoids: SELECT COUNT(*) FROM 'objects'

Also if you want to display the count using this one-liner technique you can simply write up a shorthand if/else statement as follows:

<%= @objects.try(:length).to_i > 0 ? @objects.length : "nothing found" %>

One last option:

Use the pluralize method, which can handle a nil count:

Showing <%= pluralize( @objects.try(:length), 'object' ) %>

Sorry, I know this is pretty late, but hopefully helpful for someone else!

2 Comments

That seems overly confusing and samtically wrong. If the try call returns nil, you are essentially asking if 0 is greater than 1.
Changed to use .to_i as I think it's clearer. Thanks for your feedback

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.