熱門文章

顯示具有 migration 標籤的文章。 顯示所有文章
顯示具有 migration 標籤的文章。 顯示所有文章

2016年10月31日 星期一

[Rails]資料庫可以使用哪些資料型態?如何存array,json ?

Here are all the Rails 4 (ActiveRecord migration) datatypes:
  • :binary
  • :boolean
  • :date
  • :datetime
  • :decimal
  • :float
  • :integer
  • :bigint
  • :primary_key
  • :references
  • :string
  • :text
  • :time
  • :timestamp
If you use PostgreSQL, you can also take advantage of these:
  • :hstore
  • :json
  • :array
  • :cidr_address
  • :ip_address
  • :mac_address
They are stored as strings if you run your app with a not-PostgreSQL database.
Edit, 2016-Sep-19:
There's a lot more postgres specific datatypes in Rails 4 and even more in Rails 5.

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>