2017-08-16 97 views
1

出於某種原因,我的link_to_if行能夠正常工作,但出現在我的模型(公司)的每個節目視圖中。Rails link_to_if沒有正確隱藏鏈接

下面的代碼:

<% @customers.each do |customer| %> 
    <li> 
    <%= link_to_if customer.company_id == @company.id, "#{customer.first_name} #{customer.last_name}", customer_path(customer[:id]) %> 
    </li> 
<% end %> 

問題:我有customer1錶鏈接到公司CompanyX。當我到CompanyZ時,它顯示Customer1,但鏈接不是超鏈接。它只是明文,甚至不應該顯示出來。然而,在CompanyX看來,該鏈接正常工作。我在這裏做錯了什麼?

回答

1

如果您閱讀link_to_ifhttps://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to_if)的文檔,它清楚地表明[如果爲false] 只返回名稱

在文檔中,您可以發現給定的(可選)塊在false的情況下呈現。所以你的情況,你可以通過它的空塊:

<%= link_to_if false, customer_path(customer[:id]) {} %> 

在我看來,如果你想顯示僅當從@customers一個或多個customer(S)被關聯到該@company鏈接,你應該這樣來做:

<% @customers.where(company_id: @company.id).each do |customer| %> 
    <li> 
    <%= link_to "#{customer.first_name} #{customer.last_name}", customer_path(customer[:id]) %> 
    </li> 
<% %> 
+0

出於某種原因,空塊沒有工作,但是從文檔'的link_to「登錄」,......如果@current_user .nil?'爲我工作。謝謝。 –

+1

@SamLim我強烈建議你看看我的答案的第二部分,因爲它會節省表演。在所有'@ customers'數組中循環僅僅爲'@ company'顯示匹配的'customer'是浪費性能。 – MrYoshiji

+0

是的,工作完美!非常感謝。作爲一個Rails newb,還有一個額外的問題......這種類型的邏輯應該在視圖中嗎? –

1
如果你想隱藏一些記錄,你可以從控制器做控制客戶

基於公司

@customers = Company.find(:id).customers 

然後在你的意見,你可以只顯示它沒有比較它

<% @customers.each do |customer| %> 
    <li> 
    <%= link_to "#{customer.first_name} #{customer.last_name}", customer_path(customer[:id]) %> 
    </li> 
<% end %>