Last active
August 29, 2015 14:05
-
-
Save elizabrock/871e513cdc615c8e2b0a to your computer and use it in GitHub Desktop.
Example Join Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LineItem < ActiveRecord::Base | |
belongs_to :product | |
belongs_to :order | |
before_create :set_default_quantity | |
private | |
def set_default_quantity | |
@quantity ||= 1 | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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