0
的「魔術」方法中的小寫情況模型Country
具有屬性code
,該屬性被before_save
回調自動轉換爲小寫。有沒有可能強制這種行爲的「魔術」方法,而不重寫大塊的ActiveRecord :: Base?模型
class Country < ActiveRecord::Base
attr_accessible :code
validates :code, :presence => true
validates_uniqueness_of :code, :case_sensitive => false
before_save do |country|
country.code.downcase! unless country.code.nil?
end
end
RSpec的
describe Country do
describe 'data normalization'
before :each do
@country = FactoryGirl.create(:country, :code => 'DE')
end
# passes
it 'should normalize the code to lowercase on insert' do
@country.code.should eq 'de'
end
# fails
it 'should be agnostic to uppercase finds' do
country = Country.find_by_code('DE')
country.should_not be_nil
end
# fails
it 'should be agnostic to uppercase finds_or_creates' do
country = Country.find_or_create_by_code('DE')
country.id.should_not be_nil # ActiveRecord Bug?
end
end