Article:
ActiveRecord - Custom attribute và validation
1089
ngocdaothanh.myopenid.com 172Updated 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"}>>
>>
Rails
172