Question

I have two models

class User < ActiveRecord::Base
  has_many :deals
end

and

class Deal < ActiveRecord::Base
  belongs_to :user
end

Now I want to select all those users (through active record query interface) which have non empty array of deals. I want something like this

User.select{|u| u.deals != []}

I know its very simple but please help me out cause i need it for pagination with will_paginate.

Was it helpful?

Solution 2

I know this is not a good approach but it worked for me just adding my answer perhaps it will help any one

restaurants_ids = User.all.collect{|u| u.id if (u.role == "restaurant" && !u.deals.empty?)}
@restaurants = User.where(:id=>restaurants_ids).paginate(:page => params[:page], :per_page=>1)

OTHER TIPS

There are many ways you can achieve this, but my preffered one is to write scope in your user.rb, like this

class User < ActiveRecord::Base
  has_many :deals

  scope :with_deals, lambda{
    joins(:deals).uniq
  }
}

then calling User.with_deals will return users with non-empty deals only (and you can chain any other resctrictions, because its a relation). So if you use will_paginate, then in your controller you can call:

User.with_deals.paginate(:page => params[:page])

or whatever you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top