5
Using try method to check existence of key in hash
source link: https://mednoter.com/dirty-tips-for-Rails-try-method.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Using try method to check existence of key in hash
Parameter is a hash, frequently used to transfer data. Sometimes it nests as the following structure:
:user => {:name => "Ryan", :sex => "male", :age => "28"}
To access ‘:name’ in your controller, you probably write code like this:
def name
params[:user][:name]
end
Wait! Something is wrong. Rails will raise undefined method[:name] for nil
error when param[:user] doesn’t exit
Sadly, you have to clutter your code to make it work.
def name
params[:user] ? params[:user][:name] : nil
end
Actually, you have another choice - try method. Code can also be writen as
def name
params[:user].try(:[], :name)
end
Now it works perfectly and clean.
Look up .try method of Rails.
吕小荣
03 November 2013
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK