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