我正在从rails 2.3应用程序迁移到Rails 3.1,当我尝试保存记录时,我收到此错误。这不是早些时候发生的,我不确定是什么原因,任何帮助将不胜感激,谢谢。
以下是我的模特预览
**
class Item < ActiveRecord::Base
belongs_to :order
validates_presence_of :order_id
end
**
**
ActiveRecord::RecordInvalid: Validation failed: Items order can't be blank
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/validations.rb:56:in `save!'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/attribute_methods/dirty.rb:33:in `save!'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/transactions.rb:246:in `block in save!'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/transactions.rb:295:in `block in with_transaction_returning_status'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/connection_adapters/abstract/database_statements.rb:194:in `transaction'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/transactions.rb:208:in `transaction'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/transactions.rb:293:in `with_transaction_returning_status'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/activerecord-3.1.12/lib/active_record/transactions.rb:246:in `save!'
from (irb):16
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/railties-3.1.12/lib/rails/commands/console.rb:45:in `start'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/railties-3.1.12/lib/rails/commands/console.rb:8:in `start'
from /Users/branch/.rvm/gems/ruby-1.9.3-p484/gems/railties-3.1.12/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
1
**
**
o = st.orders.new(:store_order_id => "1M",:date_time => Time.now)
**
以下是我尝试保存时的错误消息日志
**
o.save
#<Order id: nil, store_order_id: "12121M", date_time: nil>
**
当我尝试通过控制台保存订单时。主键被保存为nil。
def create
@order = @store.orders.new(params[:order])
@order.save
end
这是我在
时所看到的System.out.println("Printing statement after every 2 seconds");
下面是我的订单控制器创建代码的预览
std::vector
答案 0 :(得分:1)
你的问题是你不能这样做:
validates_presence_of :order_id
项目模型中的。原因很简单:订单ID在验证后创建,因此不存在。
有几件事要做:
以下是代码:
class Order < ActiveRecord::Base
has_many :items, :inverse_of => :order, :dependent => :delete_all
end
class Item < ActiveRecord::Base
belongs_to :order, :inverse_of => :items
validates_presence_of :order
end