Coda Chang Coda Chang - 28 days ago 6x
Ruby Question

Rails the alternative plan of rescue

I read some of article said rails

will lead performance problem.
For example

a = Course.where(id: 20).first #better
a = Course.find(20) rescue nil #worse

Then how do I rewrite the following code in best way

parent_section = parent_section.section rescue nil

I've tried this

parent_section = parent_section.section if parent_section.section.present?

It works fine, but I thought it's too long and mess.
Is there a better way to achieve that?


If the code is

parent_section_id = rescue nil

How do I rewrite it?


If this is just an Active Record association, then it shouldn't raise any exception when you call section on your parent_section. It will just return nil naturally if there isn't a section present, so you won't need the rescue at all. You should be able to replace your code with:

parent_section = parent_section.section

If you want to call something on the result (eg id) then you can use try - which will only call the method named if the thing is not nil eg:

parent_section_id = parent_section.section.try(:id)