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

Article: ActiveRecord - Custom attribute và validation 1089

Rails
ngocdaothanh.myopenid.com 172
Updated over 4 years ago
Có nhiều trường hợp định nghĩa trong cơ sở dữ liệu không nhất thiết phải trùng khớp với business logic. Trong những trường hợp thế này, ActiveRecord cho phép viết viết code rất thoải mái, cảm giác không khác trường hợp bình thường.

Custom attribute

Giả sử Student chỉ gồm first_name và last_name. Ta muốn kiểm tra định nghĩa thêm attribute tạm full_name. Ngoài ra trước khi lưu first_name và last_name vào cơ sở dữ liệu, muốn kiểm tra full_name phải dài 8 kí tự.


class Student < ActiveRecord::Base
  validates_length_of :full_name, :is => 8

  def full_name
    self.first_name + self.last_name
  end
end

Chạy thử với console:


$ruby script/console
>> s = Student.new
=> #<Student:0xb73a4438 @new_record=true, @attributes={"first_name"=>nil, "last_name"=>nil}>
>> s.first_name = 'Nam'
=> "Nam" 
>> s.last_name = 'Nguyen'
=> "Nguyen" 
>> s.save
=> false
>> s.errors
=> #<ActiveRecord::Errors:0xb739274c @errors={"full_name"=>["is the wrong length (should be 8 characters)"]}, @base=#<Student:0xb73a4438 @errors=#<ActiveRecord::Errors:0xb739274c ...>, @new_record=true, @attributes={"first_name"=>"Nam", "last_name"=>"Nguyen"}>>
>>

Custom validation

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