Vinova tuyển lập trình viên Mobile & Web ở Hà Nội, lương $300-1000

Article: Loại bỏ khoảng trắng trong field của model 1016

Rails
ngocdaothanh.myopenid.com 172
Updated over 4 years ago
Khoảng trắng trong field khi nhập từ form rất khó chịu trong đa số trường hợp. Làm cách nào để loại bỏ chúng dễ dàng?
Có thể thêm đoạn mã sau vào environment.rb.


# Reopen ActiveRecord::Base to strip white spaces for strings
class ActiveRecord::Base
  before_validation :strip_white_space

protected

  def strip_white_space
    self.attributes.each do |key, value|
      self[key].strip! if !self[key].nil? and self[key].class == String
    end
  end
end

Như vậy, chúng ta không cần sửa model sẵn có mà vẫn đạt mục đích.

Comments

You must login to be able to comment

Uploaded files

No file uploaded yet

You must login to be able to upload

Nhà tài trợ:

Mọi người đều tự do viết bài, sửa bài của người khác, và bình luận ở trang web này. Bạn muốn chủ động tạo bài mới để chia sẻ kinh nghiệm với mọi người? Xin click link ở dưới.

Create new content