type_castã«æ°ãã¤ããªãã£ããUser.new(:school_id => @school)ã¯ã ããªã®ã
ã¨ãã§ããªãè¦è½ã¨ãããã¦ããããããªãã¹ãã³ã¼ãæ¸ãã¦ãã
fixtures :pay_types def test_record o = Order.new(:pay_type_id => pay_types(:one)) assert_equal o.pay_type, pay_types(:one) ... end
ãã®ãã¹ãã¯éãã¾ããããã£ã¦ã¯ãããªãæ¸ãæ¹ã§ããä½ããããªããã¨ããã¨ãã:pay_type_id => pay_types(:one)ãã®é¨åã
以ä¸ã®ä¾ãã¿ãã¨ããããããåããã
Loading development environment. >> o = Order.new(:pay_type_id => PayType.find(2)) => #<Order:0x22f8080 @new_record=true, @attributes={"name"=>nil, "pay_type_id"=>#<PayType:0x22f8008 @attributes={"updated_at"=>"2008-01-12 12:20:07", "id"=>"2", "pay_type"=>"cc"}>, "address"=>nil, "email"=>nil}> >> o.pay_type_id => 1
ãpay_type_id => PayType.find(2)ãã£ã¦ãã£ãããããã®çµæã¯2ã«ãªãã¨æã£ã¦ã¾ããã
type_castã§å¤æããã
ä½æ
ç´åã®ä¾ã®æå¾ã2ã«ãªããªããã¨è¨ãã¨ããã£ã¹ãã«é¢ä¿ãããã¾ããão.pay_type_idãã®ããã«ãã«ã©ã ã®ãã¼ã¿ã¸ã®ã¢ã¯ã»ãµãå¼ã¶ã¨ãå
é¨çã«ã¯ãActiveRecord::Base#read_attributeãã¡ã½ããã使ããããã®ä¸ã§ãã£ã¹ããè¡ããã¾ãã
ãã£ã¹ãã¯ãããªæãã
- ActiveRecord::ConnectionAdapters::Column#type_cast
# Casts value (which is a String) to an appropriate instance. def type_cast(value) return nil if value.nil? case type when :string then value when :text then value when :integer then value.to_i rescue value ? 1 : 0 when :float then value.to_f when :decimal then self.class.value_to_decimal(value) when :datetime then self.class.string_to_time(value) when :timestamp then self.class.string_to_time(value) when :time then self.class.string_to_dummy_time(value) when :date then self.class.string_to_date(value) when :binary then self.class.binary_to_string(value) when :boolean then self.class.value_to_boolean(value) else value end end
注ç®ã¯ãwhen :integer then value.to_i rescue value ? 1 : 0ãã®é¨åãpay_type_idã®åã¯integer(MySQLã§)ã§ãããã£ã¦ããã£ã¹ããããéï¼å
ç¨ã®ãã¹ãã®ä¾ã§è¨ãã°ão.pay_type_idã®éã«ãã£ã¹ããåããï¼ã«ã¯ãto_iãã®å¤æãåãã¾ããããããvalue(ãã®ä¾ã§ã¯ãPayTypeãªãã¸ã§ã¯ãï¼ã¯ãto_iããæããªãã®ã§ãä¾å¤ãçºçããçµæã1ãæ ¼ç´ããã¾ãã
å ç¨ã®ãã¹ãã®æ¹å
ãããããå
ç¨ã®ãã¹ããä½æ
éããã¨ããã¨ããpay_types(:one).idãã®çµæããã¾ãã¾1ã ã£ãããã§ãããããããã®1ã¯ãpay_types(:one).idãã®1ã§ã¯ãªãããã£ã¹ãã§çºçããä¾å¤ã®çµæã§ããã
å®éã¯ã次ã®æ§ã«æ¸ãã¾ãã
o = Order.new(:pay_type_id => pay_types(:one).id)
次ã®ããã«ãæ¸ãã¾ãï¼ãã¾ãããããã¯ããªãï¼ã
o = Order.new(:pay_type => pay_types(:one))
ããã¯ãå
é¨ã§ã¯ão.pay_type = pay_types(:one)ãã¨å¦çãããã®ã§ãçµæã¯ä¸ã®æ¸ãæ¹ã¨åãã«ãªãã¾ãã
ã¾ããå®éã®ã³ã¼ãã§ã¯ão = Order.new(:pay_type_id => pay_types(:one))ãã®ããã«ããªãã¸ã§ã¯ããHashã®å½¢ã§æå®ãããã¨ã¯ãªãã¨æãã®ã§ããï¼Order.new(params[:order])ã¨ããå¤ããã¨ï¼ããã¹ãã³ã¼ãããã¾ãã¯ãPayType(æ¯æãæ¹æ³)ã®ããã«ã決ããããå¤ã ããæã¤ãã¼ã¿ãã¼ã¹ã使ãå ´åã¯ããã®ãããªæ¸ãæ¹ããã¦ãã¾ãããããã¾ããã