Outer Join The Rails 3 Way

I have 3 models, for example:

location, user, discovered_location(location_id,user_id) 

It seems to me that I need an external connection to get all the locations, and also include the detected model if this location was discovered by the user.

I need something like {location1, location2, location3:includes discovered_location, location4 ..}

Is there a way for Rails 3 to do this? If not, what is the best way?

EDIT

I want to get the above locations for a specific user. To better illustrate, this should be:

user {location1, location2, location3:includes discovered_location, location4 ..}

(The user has many discovered places)

+4
source share
3 answers

You need to verify that the user ID in your detected_locations table is either equal to the ID of the corresponding user or equal to zero. This is easy to accomplish with the meta_where gem. Given the following models:

 class User < ActiveRecord::Base has_many :discovered_locations has_many :locations, :through => :discovered_locations end class Location < ActiveRecord::Base has_many :discovered_locations has_many :users, :through => :discovered_locations end class DiscoveredLocation < ActiveRecord::Base belongs_to :user belongs_to :location end 

Insert some dummy data, then execute a statement, for example:

 Location.includes(:discovered_locations).where( {:discovered_locations => {:user_id => User.first.id}} | {:discovered_locations => {:user_id => nil}} ).each do |loc| puts "#{loc.name} #{loc.discovered_locations.empty? ? 'not visited' : 'visited'}" end 
+3
source

You can perform external joins in Rails only with the SQL literal in the joins method:

 joins("OUTER JOIN table2 on table2.column = table1.column") 
+7
source

Source: https://habr.com/ru/post/1344869/


All Articles