Rails "NOT NULL constraint failed: table.column"
Rails "NOT NULL constraint failed: table.column"
我有一个帐户 table,其名称和编号列有非空约束。
我在创建操作中也有 "accounts" 控制器的这段代码:
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}" }
我的 "Account" 模型非常简单:
class Account < ApplicationRecord
belongs_to :user
attr_accessor :name
attr_accessor :number
attr_accessor :amount
end
但是当我转到 /accounts/new 并提交时,它给我这个错误:
NOT NULL constraint failed: accounts.name
但是为什么呢?因为我在构造函数中用 "hello" 硬编码了 "name" 属性,所以为什么不用 "hello" 填充 "name" 列?
从 Account
中删除 attr_accessor
个调用。它们可能会覆盖从您的模式生成的内置方法,这将导致许多问题。
您是否创建并 运行 迁移以将这些属性添加到 accounts
table?
如果您有 :user_id
、:name
、:number
和 :amount
字段,则无需为它们添加 attr_accessor
。
此外,您可以在 :name
上添加模型级验证以避免 database-level
错误。
class Account < ApplicationRecord
belongs_to :user
validates :name, presence: true
end
我有一个帐户 table,其名称和编号列有非空约束。 我在创建操作中也有 "accounts" 控制器的这段代码:
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}" }
我的 "Account" 模型非常简单:
class Account < ApplicationRecord
belongs_to :user
attr_accessor :name
attr_accessor :number
attr_accessor :amount
end
但是当我转到 /accounts/new 并提交时,它给我这个错误:
NOT NULL constraint failed: accounts.name
但是为什么呢?因为我在构造函数中用 "hello" 硬编码了 "name" 属性,所以为什么不用 "hello" 填充 "name" 列?
从 Account
中删除 attr_accessor
个调用。它们可能会覆盖从您的模式生成的内置方法,这将导致许多问题。
您是否创建并 运行 迁移以将这些属性添加到 accounts
table?
如果您有 :user_id
、:name
、:number
和 :amount
字段,则无需为它们添加 attr_accessor
。
此外,您可以在 :name
上添加模型级验证以避免 database-level
错误。
class Account < ApplicationRecord
belongs_to :user
validates :name, presence: true
end