Created
April 4, 2015 17:41
-
-
Save aetherwu/5beb7bcb5a382f7facd6 to your computer and use it in GitHub Desktop.
Ruby active record JOIN
This file contains hidden or 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 Category < ActiveRecord::Base | |
has_many :posts | |
end | |
class Post < ActiveRecord::Base | |
belongs_to :category | |
has_many :comments | |
has_many :tags | |
end | |
class Comments < ActiveRecord::Base | |
belongs_to :post | |
has_one :guest | |
end | |
class Guest < ActiveRecord::Base | |
belongs_to :comment | |
end | |
---- | |
Category.all :joins => :posts | |
#SELECT categories.* FROM categories | |
INNER JOIN posts ON posts.category_id = categories.id | |
Post.all :joins => [:category, :comments] | |
#SELECT posts.* FROM posts | |
INNER JOIN categories ON posts.category_id = categories.id | |
INNER JOIN comments ON comments.post_id = posts.id | |
Post.all :joins => {:comments => :guest} | |
Category.all :joins => {:posts => [{:comments => :guest}, :tags]} | |
time_range = (Time.now.midnight - 1.day)..Time.now.midnight | |
Client.all :joins => :orders, :conditions => {'orders.created_at' => time_range} | |
Client.all :joins => :orders, :conditions => {:orders => {:created_at => time_range}} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment