Flezcano
Flezcano

Reputation: 1687

How to join hashes

Hi I want to achieve something like this :

feeds = []
following_companies.each do |follow|
  feeds = feeds + Activities.where(:company_id => follow.company_id).order("created_at DESC").limit(5)
end
feeds = feeds.order("created_at DESC")

By the point I use feeds = feeds.order("created_at DESC"), feeds its an Array and throws an exception saying undefined method order for #<Array:0x007f78032e2458>. As long as I know the where clause returns a hash ( or an ActiveRecord list, please correct me if I am wrong). I think the problem is the way I am initializing feeds. Any advise?

Upvotes: 0

Views: 105

Answers (3)

Sean Hill
Sean Hill

Reputation: 15056

What you're doing above is going to generate a ton of queries if you have any considerable number of followed companies. I'm not sure what your models looks like, but what I can glean from above is something like this:

class User < ActiveRecord::Base
  has_many :companies
end

class Company < ActiveRecord::Base
  has_many :activities
end

class Activity < ActiveRecord::Base
  belongs_to :company
end

You should be able to add a relationship on User to allow you to query all activities at once. Your user model would like something like this:

class User < ActiveRecord::Base
  has_many :companies
  has_many :activities, through: :companies
end

Then you'd be able to gather your activities by doing user.activities, which would use a join to capture all of the activities, only generating one query. Obviously, your data model may not look exactly like this, but this is the general gist of it.

Upvotes: 1

tirdadc
tirdadc

Reputation: 4703

feeds.sort_by(&:created_at).reverse will do this directly on feeds after you're done building it with your loop, but you need to do this more efficiently in the first place.

Upvotes: 1

Matthew Leonard
Matthew Leonard

Reputation: 2005

When you throw the limit on the end of the where clause, it returns an array instead of Arel. You could sort the array instead of using the arel method order.

 feeds = feeds.sort{|f| f.created_at }

Update If the following companies is still a query you can do

company_ids = following_companies.pluck(:company_id)

If it is an array, you can do this to get all the company_ids

company_ids = following_companies.map {|u| u.location_id }

You can do one query, instead of looping through, for all the feeds which will be

Activities.where(company_id: company_ids).order("created_at DESC")

I'm not sure how you would limit it to 5 for each id though.

Upvotes: 1

Related Questions