You need to join this project to post message / question. See Help for details.
try
cool
Bắt đầu từ Rails 2.3, có thể dùng try để rút ngắn bước kiểm tra đối tượng nil?
Trong mã đầu tiên, phải kiểm tra article.nil?, nếu không sẽ phát sinh lỗi NoMethodError.
1 article = Article.find_by_title("Some title")
2 unless article.nil?
3 article.body
4 end
Có thể viết thật gọn lại như sau
1 article = Article.find_by_title("Some title").try(:body) # trả về .body hoặc nil
Thật gọn nhỉ :)
Comments