AnApprentice
AnApprentice

Reputation: 110990

Given User.deleted_at, how to filter out deleted users in other models w (user_id,friend_id)?

My user model has a default scope to not show deleted users. This allows my app to soft delete users. The problem is this is causing an error in an associated model.

User.rb (id,name)
    default_scope :conditions => 'users.deleted_at IS NULL'

NavItem.rb (id,user_id, friend_id)

items = NavItem.find_all_by_user_id(current_user.id)
items.each do |item|
    user = User.find(item.friend_id)
end

The problem I'm having here is that when a user is set is deleted, meaning @user.deleted_at is NOT NULL, the query above for the user errors because no user is found.

How can I update NavItem.rb so it is joined to the User model and magically filters out users.deleted_at?

Thanks

Upvotes: 0

Views: 912

Answers (1)

Deradon
Deradon

Reputation: 1787

The following might help you.

I scaffolded this:

class User < ActiveRecord::Base
  attr_accessible :deleted_at, :name

  default_scope :conditions => 'users.deleted_at IS NULL'

  has_many :nav_items
end


class NavItem < ActiveRecord::Base
  attr_accessible :friend_id, :user_id

  belongs_to :user

  scope :without_deleted_users, where(:user_id => User.scoped)
end

And NavItem.without_deleted_users:

NavItem.without_deleted_users
  NavItem Load (0.2ms)  SELECT "nav_items".* FROM "nav_items" WHERE "nav_items"."user_id" IN (SELECT "users"."id" FROM "users" WHERE (users.deleted_at IS NULL))

Upvotes: 1

Related Questions