Rails 4保存后创建相关对象

时间:2014-09-24 21:29:59

标签: ruby-on-rails controller

我有两个带[fields]的模型:

订单[:日期] 交货槽[:日]

订单belongs_to :delivery_slot

创建订单时,我希望创建一个投放槽,并将:day设置为订单:date

到目前为止,我已在订单控制器中创建了一个新方法create_delivery_slots,该方法在创建订单时创建了一个交付时段,但我感到难过的是,如何获取订单:date交货槽:day字段?

#Create delivery slots if they dont already exist
def create_delivery_slots
  existingslots = []
  existingslots = DeliverySlot.all.select {|slot| slot.day == @order.date}
  if existingslots.empty?
    slot = DeliverySlot.new(:day => @order.date)
    slot.save!
  end

我尝试了多种方法,但没有运气。我的直觉告诉我它与强参数有关但我无法弄清楚......

1 个答案:

答案 0 :(得分:0)

我不确定你是如何设置的,但你可能想要这样的东西:

class Order < ActiveRecord::Base
  has_a :delivery_slot
  after_create => :create_delivery_slots
  .
  #other code stuffs
  .
  .
  private

  def create_delivery_slots
    existingslots = []
    existingslots = DeliverySlot.all.select {|slot| slot.day == self.date}
    if existingslots.empty?
      slot = DeliverySlot.new(:day => self.date)
      slot.save!
    end
  end
end

这是未经测试但基本上应该是你需要的。