boydenhartog
boydenhartog

Reputation: 752

How to create multiple models from one controller

I'm in the process of building my first rails app and am running into some trouble. This is my context:

I have created an api/v1/orders controller that accepts a JSON message from a third party containing an order with multiple line items. In this controller, I create the order and the multiple line items in one go, by using accepts_nested_attributes_for :line_items, allow_destroy: true.

Now, after creating the order and line items I want to create shipments. My initial thought is to create a method in the Order model because all the shipments for a specific order should be created at the same time after the order is inserted. Now how do I access the order attributes in the model?

In my controllers this is my order#create

                order = Order.new(
                  shopify_order_id: params[:id],
                  shopify_created_at: params[:created_at],
                  shopify_order_name: params[:name],
                  #etc etc
                  line_items_attributes: create_line_items(params[:line_items])
                )

After the order.save, I would like to call order.assign_shipments. How do I access the attributes that I set in my orders controller though?

In my order model I want to do something like:

    def self.assign_shipments
      order.line_items.each do |line_item| 
      #   check line item params
      #   create_shipments based on line item params
      end
    end

But, I don't know how I can access the attributes (line items) of the order? Are these even available in the model or are these only available in the instance of my orders controller (and thus should I create the shipments in my orders controller)?

Upvotes: 0

Views: 98

Answers (1)

Jeff F.
Jeff F.

Reputation: 1067

Using self. in front of the method declaration makes it a Class method. You want an instance method, since you're calling assign_shipments on an instance of Order. Then in the method use self to refer to the instance itself.

def assign_shipments
    self.line_items.each do |line_item|
        #   check line item params
        #   create_shipments based on line item params
    end
end

Upvotes: 1

Related Questions