Last active
December 21, 2015 00:29
-
-
Save rafaelcgo/6221055 to your computer and use it in GitHub Desktop.
How to make place2.rb into only 1 query?
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 Event < ActiveRecord::Base | |
belongs_to :owner, class_name: 'User', foreign_key: 'user_id' | |
belongs_to :place | |
has_many :photos, as: :parent | |
validates_presence_of :name, :owner | |
end |
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 Photo < ActiveRecord::Base | |
belongs_to :parent, polymorphic: true | |
belongs_to :owner, class_name: 'User', foreign_key: 'user_id' | |
validates_presence_of :owner, :file | |
mount_uploader :file, PhotoUploader | |
end |
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 Place < ActiveRecord::Base | |
belongs_to :owner, class_name: 'User', foreign_key: 'user_id' | |
has_many :photos, as: :parent | |
validates_presence_of :name, :city, :country, :owner | |
validates_uniqueness_of :name | |
end |
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
def all_photos | |
Photo.joins("INNER JOIN events ON events.id = parent_id") | |
.joins("INNER JOIN places ON places.id = events.place_id") | |
.where("places.id = #{id}") | |
.concat self.photos | |
end | |
Place.first.all_photos.size | |
-> SELECT "photos".* FROM "photos" INNER JOIN events ON events.id = parent_id INNER JOIN places ON places.id = events.place_id WHERE (places.id = 6) | |
-> SELECT "photos".* FROM "photos" WHERE "photos"."parent_id" = $1 AND "photos"."parent_type" = $2 [["parent_id", 6], ["parent_type", "Place"]] |
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 User < ActiveRecord::Base | |
devise :database_authenticatable, :registerable, | |
:recoverable, :rememberable, :trackable, :validatable, :token_authenticatable | |
has_many :events | |
has_many :photos | |
has_many :places | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment