Skip to content

Instantly share code, notes, and snippets.

@elizabrock
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elizabrock/871e513cdc615c8e2b0a to your computer and use it in GitHub Desktop.
Save elizabrock/871e513cdc615c8e2b0a to your computer and use it in GitHub Desktop.
Example Join Model
class CreateLineItems < ActiveRecord::Migration
def change
create_table :line_items do |t|
t.references :order
t.references :product
t.integer :quantity
t.boolean :delivered
end
end
end
order = Order.last
product1 = Product.first
order.products << product1 # Creates the appropriate line_item for this relationship
product2 = Product.last
LineItem.create(order: order, product: product2, quantity: 4)
class LineItem < ActiveRecord::Base
belongs_to :product
belongs_to :order
before_create :set_default_quantity
private
def set_default_quantity
@quantity ||= 1
end
end
class Order < ActiveRecord::Base
has_many :line_items
has_many :products, through: :line_items
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment