2014-10-30 75 views
0

我有一個小應用程序,我有一個簡單的用戶模型,我目前正在嘗試添加一些軟刪除功能(是的,我知道這裏有一些寶石)。對用戶來說工作正常,但是當我刪除一個用戶時,相關的主題視圖會崩潰,因爲我猜想由於默認範圍而無法再找到已刪除的用戶。 任何想法如何得到這個?視圖的Rails軟件與has_many協會刪除

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 %> 
+0

我沒有看到在您的控制器代碼中定義的@topics?你可以發佈該代碼嗎? – Surya 2014-10-30 19:28:21

+0

你還想顯示所有主題(活動列設置爲false的用戶的事件)? – Surya 2014-10-30 19:31:50

+0

新增主題控制器的索引,雖然它確實很容易。 – user3133406 2014-10-30 19:54:32

回答

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 

視圖將有你的主題#指數沒問題了:

<% @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

0

利用這一點,並留下協會,因爲它是。

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

這可以繞過異常很好,但仍然無法顯示相應的用戶名。 – user3133406 2014-10-30 20:09:14

+0

,因爲關聯的用戶已被刪除。解決辦法之一就是在主題中存儲用戶名。 – 2014-10-30 21:01:36