Simplify multiple nil checking in Rails

ruby check if nil or empty
rails present
check if something is nil rails
ruby check if not nil
ruby present
check for empty string rails
rails not nil
nil vs present rails

How should I write:

if @parent.child.grand_child.attribute.present?

without cumbersome nil checkings to avoid exception:

if @parent.child.present? && @parent.child.grandchild.present? && @parent.child.grandchild.attribute.present?

Thank you.

Rails has object.try(:method):

if @parent.try(:child).try(:grand_child).try(:attribute).present?

Simplify your Ruby code with the Robustness Principle, nil? Provided by Ruby; Can an be used on anything; Will return true only for nil. nil.nil? This simplifies # # !address || address.empty? Perhaps for speed of not checking if they have empty? method which they don't… Check out my other articles in this series on using acts_as_taggable_on and the devise gems with Rails 5! A quick cheatsheet so you don’t have to read the full article ;) .nil?

You could use Object#andand.

With it your code would look like this:

if @parent.andand.child.andand.grandchild.andand.attribute

nil?, empty?, blank? in Ruby on Rails, Test what happens when your method sends a message to one of its objects when There are many ways to respond to a nil value, the right one typically One way to solve this would be to use Ruby's relatively new safe navigation operator. $ rails new simplify-example Once the Rails application is created, cd into the folder, and run: $ bundle install Add the Simplify Commerce gem to your Gemfile. The first thing we need to do is to use the Simplify Commerce gem in your rails app. Open your Gemfile, and add the following line: gem 'simplify', '~> 1.1.2' Run the bundle install

You can slightly reduce it by assigning the intermediate values to some local variable:

if a = @parent.child and a = a.grandchild and a.attribute

5 Ways to Deal with Nil Headaches in Ruby, The options Ruby offers come in the form of several methods: “present? But they are also all different, in the sense that they check for different types Finally, you could use the ternary-if operator in order to simplify the code� Foo. where (name: [nil, '']) With testing, I found that the IN query above would find rows where name is an empty string but not NULL. Much to my surprise, ActiveRecord DID do what I wanted but not how I expected. Somewhere, I have yet to find the code; there must be a special case when [nil, ''] is given, the query we wanted gets produced:

For fun, you could use a fold:

[:child, :grandchild, :attribute].reduce(@parent){|mem,x| mem = mem.nil? ? mem : mem.send(x) } 

but using andand is probably better, or ick, which I like a lot and has methods like try and maybe.

Understanding Absence in Ruby: Present, Blank, Nil, Empty, Yes, it is the case that nil and false are the only falsy values in Ruby. However, if you nil end end. can be simplified to: Now you can argue that returning nil is not always the best idea, since it means checking for nil everywhere. But that is� Which means that you can string multiple scopes together without worrying about checking for nil, like this: Article.published.featured.latest_article Readability. Scopes can be written in just

If the attribute you are checking is always the same, create a method in @parent.

def attribute_present?
  @parent.child.present? && @parent.child.grandchild.present? && @parent.child.grandchild.attribute.present?


Alternatively, create has_many :through relationship so that @parent can get to grandchild so that you can use :


Note: present? is not just for nil, it also checks for blank values, ''. You can just do @parent.grandchild.attribute if it's just nil checking

Ruby: if variable vs if variable.nil?, In it you'll see a way to remove nils while dramatically simplifying some typical web Case pattern, the Null Object pattern, in order to clean up some Rails 4 code. It looks to find a current user by checking in a session object. As a dev who has sunk many an hour into combating nil values, thanks for� Layouts and Rendering in RailsThis guide covers the basic layout features of Action Controller and Action View.After reading this guide, you will know: How to use the various rendering methods built into Rails. How to create layouts with multiple content sections. How to use partials to DRY up your views. How to use nested layouts (sub-templates).

Two screencasts, two ways to eradicate Ruby nil values – RubyTapas, How to create layouts with multiple content sections. How to use partials to With the code in this form, there will likely be a problem if the @book variable is nil . Then I realised that Array(nil) returns [] so we could simplify the conditions. Notes Not sure why tests are failing Summary I first wanted to fix this condition !attachables.nil? || Array(attachables).any? since if something is not nil it will always return true instead of checking if the array has any element.

Layouts and Rendering in Rails — Ruby on Rails Guides, What your code is doing is checking, using the == operator you learned Ruby follows an order of precedence when deciding how to evaluate multiple expressions. evaluates to true when used in flow control, except for false and nil . Multiple endpoints. Sometimes you have to add several health check endpoints. Let's say you have to check the docker container health and the health of your application as a whole. Below is an example for rails.

Ruby Programming Language: comparisons & conditionals, Using Hash#fetch in Ruby for better nil handling Pulling values out of a Hash in Ruby is s. This can result in cumbersome nil checks, or our absolute favourite not necessarily how you'd solve these problems in production, but hey, There's many ways to handle this problem, for example, we could set a� Check the Ruby on Rails Guides Guidelines for style and conventions. If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue . And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome in the rubyonrails-docs mailing list .

  • Are you doing nil check? Then you don't need present?.
  • I thought it is equivalent to if !@parent.child.nil? and !@parent.child.granchild.nil? ... . Am I right?
  • No present is for checking whether it is either nil or empty. And you usually don't need nil? unless you want to distinguish nil from false.
  • Right. Thanks for clarification.
  • At the very least you should pass this knowledge into the helper.
  • Thanks, Sergio. I learn something new here. Just wonder if there's a more native way to say it.
  • @AdamNYC If you are expecting a Ruby native way, then you should not tag the question as ruby-on-rails as it has try, which is not Ruby native.
  • Thanks sawa. Either Ruby or Rails would be fine for my purposes.
  • I quite often use that too, usually with database queries for some reason, stuff like: if (u = User[id]) && u.admin?... but for more than two I use a library like ick or andand, or it can start to look messy. +1 for a really useful tip.
  • I was going to mention Ick, but I thought that it's an overkill in this case :-)
  • quite probably, but it is beautiful to behold (especially let) :-)
  • Thanks Iain and Sergio. Ick is also new for me, and it seems that I got a better answer than I asked for. :-)
  •… an article with more info