Rails 怎麼檢查 Params 存不存在?

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
791   0  
·
2017/11/27
·
1 mins read


params.has_key?()

我用過各種方法,params[:one].blank? 或是 params[:one].present? 這兩個可能是最常用的,也用了很久了,其實也沒有很大的問題,但是我現在改用

params.has_key?(:one) 

為什麼?幾個問題,但主要是一些模糊地帶,如:

  • "".blank?  # = true
  • " ".blank? # = true

所以如果 params[:one]="",這一定會被認成 blank,一般來說,不會有空白這樣的 params,但是萬一真的發生,總是麻煩,進一步,如果要百分百確定,我現在是用以下的做法:

if params.has_key?(:one) && params[:one].to_i != 0

運用 Ruby 的先來後到,先確定有這的 params,在確定這個 params 的值是正確的,這樣就萬無一失了。

Params 還有一些很酷炫的寫法,

params.dig
params = ActionController::Parameters.new(foo: { bar: { baz: 1 } })
params.dig(:foo, :bar, :baz) # => 1
params.dig(:foo, :zot, :xyz) # => nil

params2 = ActionController::Parameters.new(foo: [10, 11, 12])
params2.dig(:foo, 1) # => 11

用 Dig 在 Rails 的 form_for 中,可以用 params.dig(:user, :name),去讀 user 的 name,好不好用,看人,但是很酷!

另一個也很酷,這就一定要用了:

present_in?

簡單好用的檢查 params

locale_options = [:en, :zh-TW] 
...

params[:locale].presence_in(locale_options) || :en

 

寫這篇是為了紀念我又忘記給 AJAX 中設定 locale params ⋯⋯ 


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

Categories:
Tags:
Date:
Published: 2017/11/27 - Updated: 2017/11/27
Total: 290 words


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.