2014-04-03 65 views
1

換句話說,在我的應用程序中,我有一個索引,顯示我希望從此列表中排除current_user的總用戶數。如何從所有用戶的索引中刪除current_user?

我已經使用以下代碼來防止user.name和從成功展示user.profile_photo:

<% unless user.hidden_for?(current_user) || user.blocked_for?(current_user) || user == current_user %> 

但是,它仍然表示,顯示2個時用戶只顯示其他用戶的個人資料照片和姓名,它應該只說一個顯示用戶不包括我在那裏。

這裏是代碼行,最終需要修復:

<h4 class="events_counter"> 
      <%= @users.any? ? "Showing #{pluralize(@users.size, 'people')}" : "No users to show" %> 
      </h4> 

任何幫助將是真棒! 乾杯!

更新:(這裏是當前相關的索引操作)

class ProfilesController < ApplicationController 
    before_filter :authenticate_user! 

    def index 
    if params[:search] 
     terms = params[:search][:terms] || nil 
     min_age = params[:search][:age_min] || nil 
     max_age = params[:search][:age_max] || nil 
     zipcode = params[:search][:zipcode] || nil 
     distance = params[:search][:distance] || nil 
     education_id = params[:search][:education_id] || nil 
     # @ethnicity_id = params[:search][:ethnicity_id] || nil 
     ethnicity_ids = params[:search][:cat_ids].split('').uniq || nil 
     gender = params[:search][:gender] || nil 
     @users = User.active.scoped_by_search(terms, min_age, max_age, education_id, ethnicity_ids, gender) 
    else 
     @users = User.active.page params[:page] 
    end 
    end 

回答

1

隨着Rails 4.x

假設你的動作名稱是index你設置@users實例變量,你可以這樣做:

def index 
    #... 
    @users = User.active.scoped_by_search(terms, min_age, max_age, education_id, ethnicity_ids, gender).where.not(id: current_user.id) 
    else 
    @users = User.active.where.not(id: current_user.id).page params[:page] 
    #... 
end 

在這裏,如果你有一個current_user然後@users將精讀除current_user以外的所有用戶。否則,@users將擁有所有用戶。

而且,你不需要任何檢查,在你看來,即

<% unless user.hidden_for?(current_user) || user.blocked_for?(current_user) || user == current_user %> 

不再需要,所以你可以放心地將其刪除。

此外,@users.size將給予其他用戶(不包括current_user)正確的計數。

+0

@ user3399101感謝分享'索引'行動。我已經相應地更新了答案。讓我知道這是否有效。 –

+0

就是這樣,謝謝! – user3399101

+1

很高興幫助:) –

1

推薦在查詢中不包括current_user而不是視圖。例如,在控制器:

@users = User.where('id != ?', current_user.id) 

然而,如果你需要保持@users數組中的當前用戶,然後,用reject排除當前用戶爲:

@users.reject { |u| u.id == current_user.id } 
+0

謝謝!不幸的是,我收到了拒絕的Nilclass錯誤,我用當前的索引操作更新了帖子,希望有所幫助。乾杯! – user3399101

0

我建議建立一個新的可見光用戶數組。

以下是根據您當前的邏輯和數組獲取該數組的方法。

visible_users = @users.reject{|user| user.hidden_for?(current_user) || user.blocked_for?(current_user) || user == current_user} 

希望有幫助。

相關問題