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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With