使用has_many关联进行Rails软删除

时间:2014-10-30 19:10:36

标签: ruby-on-rails

我有一个小应用程序,我有一个简单的用户模型,我正在尝试添加一些软删除功能(是的,我知道有一些宝石为此)。适用于用户,但是当我删除用户时,相关的主题视图会崩溃,因为我猜不到由于默认范围而无法找到已删除的用户。 知道如何解决这个问题吗?

class User < ActiveRecord::Base
 has_many :topics
 has_many :comments
 default_scope { where(active: true) }
end

def index
 @topics=Topic.all
end

class UsersController < ApplicationController
 def index
  if current_user and current_user.role == "admin"
    @users=User.unscoped.all
     else
      @users=User.all
  end 
end

视图的一部分(topic.user.name停止工作):

<% @topics.each do |topic| %>
  <tr>
    <td><%=link_to topic.title, topic %></td>
    <td><%=h topic.description %></td>
    <td><%= topic.user.name %></td>
    <td><%=h topic.created_at.strftime('%Y %b %d %H:%M:%S') %></td>
    <td><%=h topic.updated_at.strftime('%Y %b %d %H:%M:%S') %></td>
  </tr>
<% end %>

2 个答案:

答案 0 :(得分:0)

使用此选项,并保持关联原样。

<td><%= topic.user.try(:name) %></td>

答案 1 :(得分:0)

这就是default_scope是邪恶的原因。到现在为止,你已经意识到拥有default_scope可能会导致野鹅追逐。

您可以将 user.rb 更改为:

class User < ActiveRecord::Base
  has_many :topics
  has_many :comments
  scope :active, -> { where(active: true) }
  scope :inactive, -> { where(active: false) } # can be used in future when you want to show a list of deleted user in a report or on admin panel.
end

然后是控制器:

class UsersController < ApplicationController
  def index
    @users = User.scoped
    @users = @users.active if current_user && current_user.role != 'admin'
  end
end

查看您的主题#index now现在没有问题:

<% @topics.each do |topic| %>
  <tr>
    <td><%=link_to topic.title, topic %></td>
    <td><%=h topic.description %></td>
    <td><%= topic.user.name %></td>
    <td><%=h topic.created_at.strftime('%Y %b %d %H:%M:%S') %></td>
    <td><%=h topic.updated_at.strftime('%Y %b %d %H:%M:%S') %></td>
  </tr>
<% end %>

每当您想要显示活跃用户时,只需执行:@users = User.active

相关问题