0

我的用户模型具有不显示已删除用户的默认范围。这允许我的应用软删除用户。问题是这会导致相关模型出现错误。

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 不是空的,上面的用户错误查询是因为没有找到用户。

如何更新 NavItem.rb 使其加入 User 模型并神奇地过滤掉 users.deleted_at?

谢谢

4

1 回答 1

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))
于 2012-09-26T22:42:58.480 回答