熱門文章

2016年10月8日 星期六

[Rails]ActiveRecord::Migration - 改變欄位資料型態

Step 1:
Generate a new migration file using this code:
rails g migration sample_name_change_column_type
Step 2: 
Go to /db/migrate folder and edit the migration file you made. There are two different solutions.
  1. def change
        change_column(:table_name, :column_name, :new_type)
    end
2.
    def up
        change_column :table_name, :column_name, :new_type
    end

    def down
        change_column :table_name, :column_name, :old_type




    end
Step 3:
Don't forget to do this command:
rake db:migrate


實際操作:
在command 下,新增migration 檔案
➜  eat git:(master) rails g migration sample_name_change_column_type
Running via Spring preloader in process 74424
      invoke  active_record

      create    db/migrate/20161008204016_sample_name_change_column_type.rb

在sublime text 開啟

自行修改欄位,依序是資料表名稱、欄位名稱、新的資料型態。

在此示範的是將 reviews資料表裡的rating欄位改成float 資料型態。
 change_column(:table_name, :column_name, :new_type)



在command 下

➜  eat git:(master) rake db:migrate
== 20161008204016 SampleNameChangeColumnType: migrating =======================
-- change_column(:reviews, :rating, :float)
   -> 0.0064s

== 20161008204016 SampleNameChangeColumnType: migrated (0.0065s) ==============


在rails c 下測試
可以看到紅色處由integer改為float

irb(main):002:0> a = Review.last
  Review Load (0.2ms)  SELECT  "reviews".* FROM "reviews" ORDER BY "reviews"."id" DESC LIMIT ?  [["LIMIT", 1]]
=> #<Review id: 14, rating: 3, comment: "3.5", created_at: "2016-10-08 08:15:48", updated_at: "2016-10-08 08:15:48", user_id: 3, store_id: nil>
irb(main):003:0> a.rating.class
=> Fixnum
irb(main):004:0> a.rating.class
=> Fixnum
irb(main):005:0> exit
➜  eat git:(master) rails c
Running via Spring preloader in process 74494
Loading development environment (Rails 5.0.0.1)
airb(main):001:0> a= Review.last
  Review Load (0.2ms)  SELECT  "reviews".* FROM "reviews" ORDER BY "reviews"."id" DESC LIMIT ?  [["LIMIT", 1]]
=> #<Review id: 14, rating: 3.0, comment: "3.5", created_at: "2016-10-08 08:15:48", updated_at: "2016-10-08 08:15:48", user_id: 3, store_id: nil>

irb(main):002:0> 





沒有留言:

張貼留言