Last active
August 29, 2015 14:05
-
-
Save jose8a/9c1a13b7d2627858b62d to your computer and use it in GitHub Desktop.
Rails: Methods gained via Associations
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 belongs_to Customer ==> methods gained: | |
@order.customer | |
@order.customer= | |
@order.build_customer(customer_number: 123, customer_name: "Joe Blow") --> only creates customer instance ... does not save! | |
@order.create_customer((customer_number: 123, customer_name: "Joe Blow") --> creates instance and saves it! | |
@order.create_customer!( ... ) --> raises error if record is not valid | |
//***** ------- Customer has_many Orders ==> methods gained: | |
@orders = @customer.orders | |
@customer.orders << (@order1, @order2, ...) --> //adds orders to collection | |
@customer.orders.delete(@order1, @order2, ...) --> deletes from collection by setting foreign key to NULL | |
@customer.orders.destroy(@order1, @order2, ...) --> deletes by calling destroy on each object | |
@customer.orders=objects --> forces collection to only contain "objects" | |
@customer.order_ids --> returns array of 'ids' in the collection | |
@customer.order_ids=ids --> forces collection to contain only orders with the given ids | |
@customer.orders.clear --> removes all orders from the collection | |
@customer.orders.empty? --> checks to see if 'orders' collection is empty | |
@customer.orders.size --> returns the # of orders in the collection | |
@customer.orders.find(...) --> finds objects within the collection | |
@customer.orders.where(...) --> finds objects in collection based on conditions given | |
@customer.orders.exists?(...) --> checks if object exists in collection based on conds. given | |
@customer.orders.build(attributes = {}, ...) --> returns one or more methods based attrs | |
@customer.orders.create(attributes = {}) --> returns & saves object(s) based on attrs | |
@customer.orders.create!(attributes = {}) --> raises "invalid" if record is invalid | |
//***** ------- Part has_and_belongs_to_many Assemblies ==> methods gained: | |
// The xxact same methods as the has_many association, but it goes both ways for the objects in question | |
@part.assemblies ... etc | |
@assembly.parts ... etc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment