我有一個帳號表,其名稱和編號列上沒有空約束。 我也有這樣的一段代碼爲「賬戶」控制器創建行動:Rails「NOT NULL約束失敗:table.column」
def create
account_number = rand.to_s[2..9]
@account = Account.new(user_id: current_user.id, name: 'hello', number: account_number)
respond_to do |format|
if @account.save
format.html { redirect_to @account, notice: "Account was successfully created.\n Your account number is: #{account_number}" }
和我的「賬戶」的模式很簡單:
class Account < ApplicationRecord
belongs_to :user
attr_accessor :name
attr_accessor :number
attr_accessor :amount
end
但是,當我去/帳號/新並提交,它給了我這個錯誤:
NOT NULL constraint failed: accounts.name
但是爲什麼?因爲我在構造函數中用「hello」硬編碼了「name」屬性,所以爲什麼不用「hello」填充「name」列?
可以請你發佈表架構 –
我最後的遷移是: 類AddAccountsNotNullConstraint <的ActiveRecord ::遷移[5.0] 高清更改 change_column:帳戶,:名稱,:編號,日期null =>假 結束 結束 其中也破壞了從字符串到「十進制」的「名稱」的類型 –