鉴于User.deleted_at,如何过滤掉其他模型中的已删除用户w(user_id,friend_id)?

时间:2012-09-26 21:45:47

标签: ruby-on-rails ruby-on-rails-3 activerecord

我的用户模型的默认范围是不显示已删除的用户。这允许我的应用程序软删除用户。问题是这导致关联模型出错。

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

我遇到的问题是,当设置用户被删除时,意味着@ user.deleted_at为NOT NULL,上面的查询是因为没有用户找到用户错误。

如何更新NavItem.rb以便它加入用户模型并神奇地过滤掉users.deleted_at?

由于

1 个答案:

答案 0 :(得分:1)

以下内容对您有帮助。

我支持这个:

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

和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))