Select from one table with two foreign keys in a single query

67 views Asked by At

I have tow tables:

User:
user_id

user_blogs:
user_id | blog_id

blogs:
blog_id | source | identifier

Comments:
source | identifier | Field3

I want to be able to select all comments in the blogs that a user owns.

My models are related:

class User < ActiveRecord::Base
  has_many :user_blogs
  has_many :blogs, trhough: :user_blogs
end

class blogs < ActiveRecord::Base
  has_many :comments, 
           :foreign_key => :source,
           :primary_key => :source,
           :conditions => Proc.new {
              {:identifier=> self.identifier}
           }
end

Right now I can retrieve all user comments using this:

User.first.blogs.map{|b| b.comments}

But this creates one query for each blog.

Is there a way to do this in one single step?

2

There are 2 answers

0
coorasse On BEST ANSWER
class User < ActiveRecord::Base
  has_many :user_blogs
  has_many :blogs, through: :user_blogs
  has_many :comments, through: :blogs
end

class Blog < ActiveRecord::Base
  has_many :comments, -> { where(identifier: identifier) }, foreign_key : source, primary_key: source
end


User.find(ID).comments
0
Arup Rakshit On

Yes, you need to use Rails eager_loading feature.

u = User.includes(blogs: :comments)
# now you can do
u.first.blogs.map { |b| b.comments }

Or, you can modify your model association definition also :

class User < ActiveRecord::Base
  has_many :user_blogs
  has_many :blogs, -> { includes(:comments) }, through: :user_blogs
end

Now, you can do the below without hitting multiple queries for each blog.

User.first.blogs.map { |b| b.comments }