Reputation: 1488
I have a User model that has_one
profile. I have the following code in my User model:
class User < ActiveRecord::Base
scope :city, lambda { |user| joins(:profile).where(:profiles => {:city => user.profile.city})}
end
Then in my index action of the Users controller:
def index
@users = User.city(current_user).paginate :page => params[:page], :per_page => 20
end
This allows me to fetch all users from the same city as the current_user
. What I'd also like to do is to fetch only those users that have a profile picture uploaded. I am using paperclip and the image columns are in the Users table. I wanted to add something like show users where image_file_name != nil
. However the scope above includes the profiles tables. How can I merge the query to include a column from the Users table and one from the profiles table?
Upvotes: 0
Views: 147
Reputation: 16084
You can join scopes together in Rails to form a final query.
class User < ActiveRecord::Base
scope :city, lambda { |user| joins(:profile).where(:profiles => {:city => user.profile.city})}
scope :with_pictures, where('users.image_file_name IS NOT NULL')
end
Assuming that's what your database uses to find not-null columns.
And then in your controller:
def index
@users = User.city(current_user).with_pictures.paginate :page => params[:page], :per_page => 20
end
Upvotes: 3