开发者

Rails 3: Avoiding nested ifs when testing for nested parameters

开发者 https://www.devze.com 2023-03-08 00:11 出处:网络
In rails, if I test for a nested parameter and there is no :parent assigned, it will throw an error. So, for example,

In rails, if I test for a nested parameter and there is no :parent assigned, it will throw an error. So, for example,

   params[:page][:childpage][:grandchildpage].present?

throws 'You have a nil object where you didn't expect it' if there's no :page or :childpage. Similarly,

   demopage = @page.childpage.grandchildpage.present?

throws something similar.

The solution which dare not show it's face is a whole bunch of nested if statements, which obviously isn't good enough. So, the question is...what's the standa开发者_StackOverflowrd (elegant) way of returning false instead of throwing an error should any parent element be blank? A rescue method, or is there something better?

I'm guessing this is pretty common, just wondering what the standard solution is.

Cheers...


For the second one you can use and statements.

demopage = @page &&
  @page.childpage &&
  @page.childpage.grandchildpage &&
  @page.childpage.grandchildpage.present?
0

精彩评论

暂无评论...
验证码 换一张
取 消