Search code examples
mysqlpostgresqlactiverecordruby-on-rails-4will-paginate

select all the records have non empty associated records


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.


Solution

  • 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)