PostgreSQL 踩雷記 + bundle exec

本日第一個雷:PostgreSQL的 string 轉integer

Yeng Tsan
3 min readJul 15, 2016

在Rails 中,無法快快樂樂的使用習慣的語法

class ChangeUserIdFromStringToIntegerOnTableCompany < ActiveRecord::Migration[5.0]
def change
change_column( :companies, :user_id, :integer)
end
end

會噴出錯誤訊息!

搜尋錯誤的關鍵訊息「PG::DatatypeMismatch: ERROR: column “user_id” cannot be cast automatically to type integer」

或是一行寫法

change_column :yourtable, :column_to_change, 'integer USING CAST("column_to_change" AS integer)'

第二個雷:database configuration does not specify adapter

在專案clone到Linode後,bundle的安裝是without test 與 development的

bundle install --deployment --without test development

因此,在主機執行 rake db:migrate時,會因為bundle install時 --without test dvelopment而不知道自己的環境,而跳出「database configuration does not specify adapter」

解決方法:

RAILS_ENV=production bundle exec rake db:migrate

RAILS_ENV=production 透過ENV的設定,指定是production 模式!

額外補充

bundle exec是解決「套件相依性」部分的問題。gemfile中的gem版本與執行腳本中指定的gem版本可能不一致。而bundle exec會執行腳本中指定的gem版本,將因相依gem產生的bug因素給去除!

舉例來說,如果你用gem install rake安裝了10.1.0版本的rake(假設是最新的),當你直接使用調用rake時,使用的會是這個最新版本的rake。如果項目的Gemfile中指定的版本是0.9.6(或者是Gemfile.lock中是0.9.6)的話,你如果不加bundle exec,將會用rake 10.1.0的版本去執行本來應該由0.9.6版本的rake寫出的Rake task。https://ruby-china.org/topics/13571

來看看bundle的官方說法

--

--

Yeng Tsan
Yeng Tsan

Written by Yeng Tsan

Software developer, Career consultant, Product manager.開啟你的海外職涯,從日本開始 https://engineer.taiwan-career.com/

No responses yet