Harakiri
Harakiri

Reputation: 730

Rails: Association between models

I'm pretty new to Rails so not everything is very clear to me. I have the following models.

class Order < ActiveRecord::Base
   has_many :sales
   belongs_to :user
end

class Sale < ActiveRecord::Base
   has_many :brands
   belongs_to :warehouse
   belongs_to :user
   belongs_to :order
end

What I want to do is to connect those 2 models, so every Sale has a parent Order_ID. How would you do this in your controller? I'm confused. Thank you guys!

Upvotes: 1

Views: 243

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

You should look up how to create a has_many/belongs_to association:

enter image description here

To get what you want, you'd use the following:

#app/models/order.rb
class Order < ActiveRecord::Base
   has_many :sales
end

#app/models/sale.rb
class Sale < ActiveRecord::Base
   belongs_to :order
end

You'll need to set the foreign_key of the Sale model, so that each time you invoke a @sale object, it will be associated to an @order:

$ rails g migration AddForeignKeyToSales

#db/migrate/add_foreign_key_to_sales________.rb
class AddForeignKeyToSales < ActiveRecord::Migration
   def change
       change_table :sales do |t|
         t.references :order, after: :id
       end
   end
end 

$ rake db:migrate

This will set the sale table to include the order_id foreign key, which you can then use with the following controller setup:

#config/routes.rb
resources :orders do
   resources :sales #-> url.com/orders/:order_id/sales/new
end

#app/controllers/sales_controller.rb
class SalesController < ApplicationController
   def new
      @order = Order.find params[:order_id]
      @sale = @order.sales.new
   end

   def create
      @order = Order.find params[:order_id]
      @sale = @order.sales.new order_params
      @sale.save
   end
end

Upvotes: 4

Related Questions