2014-10-30 5 views
0

간단한 사용자 모델이있는 작은 응용 프로그램이 있는데 현재 일부 소프트 삭제 기능을 추가하려고합니다 (예, 여기에 몇 가지 보석이 있음을 알고 있습니다). 사용자를 위해 잘 작동하지만 사용자를 삭제할 때 추측 된 기본 범위로 인해 삭제 된 사용자를 더 이상 찾을 수 없기 때문에 연결된 항목보기가 축소됩니다. arround를 얻는 방법에 대한 아이디어가 있으십니까?레일 소프트 삭제 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

+0

또한 모든 항목 (활성 열이 false로 설정된 사용자의 이벤트)을 표시 하시겠습니까? – Surya

+0

주제가 컨트롤러 인덱스를 추가했습니다. 실제로는 매우 쉽습니다. – user3133406

답변

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

이것은 예외를 무시할 수 있습니다 꽤 그래도, 여전히 corrensponding 사용자 이름을 표시 할 수 없습니다. 관련된 사용자가 삭제되었으므로 – user3133406

+0

입니다. 한 가지 해결 방법은 주제에 사용자 이름을 저장하는 것입니다. –