We have images on our site which users can select as profile images for their accounts. Here are the relevant lines in the models:
class User < ApplicationRecord
has_one :profile_image, dependent: :destroy
has_one :image, through: :profile_images
accepts_nested_attributes_for :profile_image, allow_destroy: true
end
class Image < ApplicationRecord
has_many :profile_images, dependent: :destroy
has_many :users, through: :profile_images
end
class ProfileImage < ApplicationRecord
belongs_to :image
belongs_to :user
validates :user_id, presence: true, allow_nil: false, uniqueness: true
validates :image_id, presence: true, allow_nil: false
end
I'd like to add an option to the User index view to only show Users with profile images. I'm searching with where.not(profile_image: nil)
in the controller, but I just get all users back.
In the console, I can confirm that I have users with and without profile images:
>> User.first.profile_image
=> nil
>> User.second.profile_image
=> #<ProfileImage id: 2, image_id: 9, user_id: 6, created_at: "2019-10-26 17:52:37", updated_at: "2019-10-26 17:52:37">
But I get the same totals from User.all.count
and User.where.not(profile_image: nil).count
.