这是我的迁移
create_table :customers do |t|
t.string "name", :limit => 25 , :null => false
t.string "email", :limit => 25, :null => false
t.string "question", :limit => 255 , :null => true
t.integer "status", :limit => 1, :default => 0, :null => false
t.timestamps
end
现在,在模型中,我想使用以下代码插入一个值:
Customers.new(:name => name, :email => email, :question => question, :status => 1)
但是表中没有插入值,为什么?
答案 0 :(得分:2)
因为您实际上没有保存。
customer = Customer.new(:name => name, :email => email, :question => question, :status => 1)
if custom.save
// Saved succefully
else
// Failed to save
end
或者只使用create
代替
customer = Customer.create!(:name => name, :email => email, :question => question, :status => 1)
在create
之后爆炸,如果失败则会引发错误。
答案 1 :(得分:0)
如果您想插入一行,则需要使用创建方法,如下所示
Customers.create(:name => name, :email => email, :question => question, :status => 1)
否则你需要创建新对象然后需要使用save方法在DB中创建一个新记录,如下所示
customer = Customers.new(:name => name, :email => email, :question => question, :status => 1)
customer.save
如果您需要更多说明,请与我们联系。