Skip to content

Instantly share code, notes, and snippets.

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 JamesDullaghan/5521777 to your computer and use it in GitHub Desktop.
Save JamesDullaghan/5521777 to your computer and use it in GitHub Desktop.
ActiveRecord Schneems Tutorial Notes on JOINS

#ActiveRecord Schneems tutorial notes#

##Joins##

class Product < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :products
end

prods = Product.joins(:user).where(:users => {:name => "Richard"}).first

Here the database creates a virtual table which allows me to access the user table

  • I am telling rails to grab me the products, from the products table, where the users name is Richard, which is located in a different table (users)
  • Select the first result from users table whos name is "Richard", and return me all of the products associated with him

###This is called an inner join Most common/default for rails. Most people use these.

In order for this to be completed, three things need to exist:

  • All of the users with an id
  • All of the products with a user_id
  • Join them together, so the products with a user_id need to match that of users with an id

Becomes a little bit exclusive.

What if we want to find a product with no users? User will return as nil. We can query the product table for a user_id of nil!!

What if we wanted to find a user with no products? Not going to be in the virtual table, so returns nil.

###Inner join###

  • Excludes relationships that don't exist
  • Think of inner join as an exclusive club, like the inner circle

###Outer join### Take all the users and match them up with a product, EVEN IF NO MATCHING PRODUCT EXISTS

Only one out of the earlier 3 for an outer join

All users with an id

User.create(:name => "chuck testa")

User.where(:name => "chuck testa").first
=> #<User id: 1802, name: "chuck testa", job_title: nil ... >

User.joins("LEFT OUTER JOIN products ON users.id = products.user_id").where(:products => {:id => nil})

###WHAT HAPPENS WHEN:

User.count
=> 1802

Product.count
=> 2403

User.joins(:products).count
=> 2401 ????

Why was that? We are counting the number of times a user_id from products, and an id from user match. There are 2 different products that are not owned by a user.

JOIN can be hard. A little bit to wrap mind around. Extremely useful and powerful. Think of it as building virtual tables.

GO SLOW, USE REFERENCE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment