2016-04-22 35 views
0

我現在有一張桌子,顯示一組用戶的屬性。這是我的問題。每個人都有能力註冊一個組,但在某些邊緣情況下,一個人可以在沒有註冊到組的情況下進入桌面。爲了清楚讀取表格的用戶,我想簡單地將每個未註冊表的人員從表格中隱藏起來。這比我預想的要複雜一些。我會展示一些代碼和截圖,以便更好地理解。從視圖中隱藏數據庫中的信息。 - Rails

enter image description here

,你可以看到,如果一個人沒有組不顯示錶。

我試圖做一個方法,並在繪製表的控制器上調用它。人員和組是兩個不同的模型與HABTM的協會。如何在ruby中說「如果沒有人不在桌子上展示」?

def index 
@people = Person.order(sort_column => sort_direction) 
@groups = Group.all 
end 

這是使表

<table class="table table-striped"> 
<thead> 
    <tr> 
    <th><%= sortable 'phone_number', 'Phone Number'%></th> 
    <th><%= sortable 'subscribed', 'Subscribed'%></th> 
    <th><%= sortable 'city' %></th> 
    <th><%= sortable 'state' %></th> 
    <th><%= sortable 'zip' %></th> 
    <th><%= sortable 'country' %></th> 
    <th><%= sortable 'created_at', "Joined" %></th> 
    <th>Groups</th> 

    </tr> 
</thead> 
    <tbody> 
    <% @people.each do |person| %> 
     <tr> 
     <td><%= person.phone_number %></td> 
     <td><%= person.subscribed? ? "Yes" : "No" %></td> 
     <td><%= person.city %></td> 
     <td><%= person.state %></td> 
     <td><%= person.zip %></td> 
     <td><%= person.country %></td> 
     <td><%= time_ago_in_words person.created_at %> ago</td> 
     <td><%= person.groups.order(:id).pluck(:name).to_sentence %></td> 
     </tr> 
    <% end %> 
    </tbody> 
控制器

組模型

class Group < ActiveRecord::Base 
has_and_belongs_to_many :people 
has_and_belongs_to_many :messages 
end 

perons模型

class Person < ActiveRecord::Base 
    has_many :deliveries 
    has_and_belongs_to_many :groups 
+0

,你能告訴我們你的看法(?在那裏你通過循環的人 - 我猜)? – Anthony

+0

如果你在團體和人之間有任何關聯,你是否也可以表明這一點? – sahil

回答

2

這些選項是O(n^2),並拉入相當多的內存,只要你確定,這些都很容易實現:

你有兩個選擇,一個爲你的觀點:

<% @people.each do |person| %> 
    <% next if person.groups.blank? %> 
    <tr> 
    <td><%= person.phone_number %></td> 
    <td><%= person.subscribed? ? "Yes" : "No" %></td> 
    <td><%= person.city %></td> 
    <td><%= person.state %></td> 
    <td><%= person.zip %></td> 
    <td><%= person.country %></td> 
    <td><%= time_ago_in_words person.created_at %> ago</td> 
    <td><%= person.groups.order(:id).pluck(:name).to_sentence %></td> 
    </tr> 
<% end %> 

或者你可以在你的控制器進行過濾:

@people = Person.order(sort_column => sort_direction).to_a.keep_if { |person| person.groups.present? } 
+0

感謝在視圖中的作品,但我想將其過濾到控制器。但是當我嘗試那個你建議它給我一個錯誤「keep_if」沒有定義? – Bitwise

+0

非常感謝你! – Bitwise