我正在使用Rails 3.2实现一个简单的飞行预订系统但是当我想保存一个可能有很多乘客的订单时遇到问题。也就是说,他们两个是一对多的关系。这是Passenger的模型。
class Passenger < ActiveRecord::Base
attr_accessible :accident_number, :cred_number, :cred_type, :delay_number, :name, :order_id
validates :cred_type, :cred_number, :name, presence: true
belongs_to :order, :inverse_of => :passengers
end
这是订单的模型
class Order < ActiveRecord::Base
attr_accessible :contact_email, :contact_name, :contact_phone, :flight_id, :print_time, :remark
validates :contact_email, :contact_name, :contact_phone, :flight_id, :print_time, presence: true
belongs_to :flight
has_many :passengers, :dependent => :destroy, :inverse_of => :order
accepts_nested_attributes_for :passengers, :allow_destroy => true
attr_accessible :passengers_attributes, :allow_destroy => true
end
参数是这样的
Parameters: {
"passengers"=>{"new_1"=>{"name"=>"Passenger 1", "cred_type"=>"ID card",
"cred_number"=>"12345", "accident_number"=>"1", "delay_number"=>"1"},
"new_2"=>{"name"=>"Passenger 2", "cred_type"=>"ID card", "cred_number"=>"54321", "accident_number"=>"1", "delay_number"=>"1"}},
"order"=>{"contact_name"=>"Contact 1", "contact_phone"=>"123456", "contact_email"=>"test2@tset,com", "print_time"=>"1", "remark"=>""},
"commit"=>"Create Order"}
问题是订单和乘客无法挽救。我已经尝试了一些方法,但他们无法解决它......例如
def create
@order = Order.new(params[:order])
respond_to do |format|
if @order.save
params[:passengers].each do |k, v|
@order.passengers.create(v)
end
先感谢您!!