Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch only the confirmed users when using devise and Sunspot?

I'm fetching all the users by this now.
However, I want to exclude non-confirmed users.
Their confirmed_at attribute is nil.

How can I?

@search = User.search do  
    fulltext params[:search]
    paginate :page => params[:page], :per_page => 10
end  

@users = @search.results
like image 676
MKK Avatar asked Feb 18 '23 15:02

MKK


2 Answers

First add a scope to your User model:

scope :confirmed, where("confirmed_at IS NOT NULL")

Then you have just to add the scope before the search

@search = User.confirmed.search do  
  fulltext params[:search]
  paginate :page => params[:page], :per_page => 10
end 

EDIT:

Indeed, after a test, the solution above don't seem to work. The scope seems to be ignored. There's another solution:

In your User model you probably have a method like this:

searchable do 
  text :lastname, :firstname
  ...
end

You have to add a condition to searchable:

searchable if: proc { |user| user.confirmed? } do 
  text :lastname, :firstname
  ...
end

EDIT 2:

There is another way if sometimes you want confirmed users and sometimes all users, but you need to modify you model too.

In you User model:

searchable do 
  text :lastname, :firstname
  boolean :confirmed do
    confirmed_at != nil
  end
  ...
end

Then in your controller

@search = User.search do  
  fulltext params[:search]
  with(:confirmed, true) # true if you want confirmed users, false for unconfirmed and if you want all users you don't write this line
  paginate :page => params[:page], :per_page => 10
end 

I hope this help

like image 82
CupraR_On_Rails Avatar answered Feb 20 '23 03:02

CupraR_On_Rails


I use User.where.not(confirmed_at: nil). You can create a scope in your model to make it easier:

class User < ApplicationRecord

  scope :confirmed, -> { where.not(confirmed_at: nil) }

end

and then you can use User.confirmed

like image 27
sandre89 Avatar answered Feb 20 '23 03:02

sandre89