Ruby会自动将Lineitems填充到订单中

时间:2014-03-11 22:39:36

标签: ruby-on-rails arrays associative-array

相当陌生的Ruby,我已经环顾四周但却找不到任何相关内容...

我在Orders,Lineitems和Items之间有一个典型的has_many-through关系。我希望能够在将订单保存到数据库时自动创建包含订单的Items表中每个项目的lineitem列表。

我正在考虑一个循环,它将循环遍历Items表中的每个项目,并为每个项目保存一个新的Lineitem记录,但不太确定如何实现它。

我知道在创建订单后,可以使用after_save回调来初始化方法。

以下是Orders模型中方法的思考过程......

items.each do |x|
  Lineitem.new(order_id=>@order.id,item_id=>x.id)
  Lineitem.save!
end

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

基于此:

  

我希望能够在订单保存到数据库时自动为订单自动创建包含Items表中每个项目的lineitem列表

您可以使用回调来处理此问题。你不必做循环:

class Order < ActiveRecord::Base
  before_create :add_lineitems

private
  def add_lineitems
    # This will associate all items in the items table with the new order.
    # It'll automatically add records to the lineitems table.
    self.item_ids = Item.pluck(:id)
  end
end