2013-08-16 73 views
0

Ruby on Rails應用程序,我有一個帶有超鏈接的「Bootstrap」圖像行。我只想顯示那些有內容的人。如果,否則elsif,否則如果只在非空時顯示對象

這裏有一個例子:如果else語句是好的

<div class="span3"> 
    <h5 class="pagination-centered"> 
     <%= link_to (image_tag "/img/folder.jpg", alt: "Buyer's Guides", width: "75px"), action: "index", filter: @filter, type: "buyers_guides" %> 
     <%= link_to "Buyer's Guides", action: "index", filter: @filter, type: "buyers_guides" %> 
    </h5> 
</div> 
<div class="span3"> 
    <h5 class="pagination-centered"> 
     <%= link_to (image_tag "/img/folder.jpg", alt: "Datasheets", width: "75px"), action: "index", filter: @filter, type: "datasheets" %> 
     <%= link_to "Datasheets", action: "index", filter: @filter, type: "datasheets" %> 
    </h5> 
</div> 

會使用?否則,如果,elsif?

或者控制器呢?

class Users::MarketingController < ApplicationController 
def index 
    @filter = params[:filter] 
    @type = params[:type] 

if @filter 
     if @type  
     arrays_of_strings_to_check_against = ['logos', 'datasheets', 'buyers_guides', 'videos', 'web_banners', 'presentations', 'documents', 'press_releases' ] 

     if arrays_of_strings_to_check_against.any?{ |o| @type =~ /\b#{Regexp.escape(o)}\b/ } 
      base_dir = "public/files/marketing" 
      @files = Dir.glob("#{base_dir}/voip/#{@filter}/#{@type.downcase}/*.[a-z]*") 
      @view = "files" 
     else  
      @view = 'types' 
     end 
    else 
     @view = 'types' 
    end 
else 
    @view = "category" 
end 
end 

這個新的和努力學習的良好做法。 謝謝

回答

3

是的,if/else通常在這種情況下使用,雖然肯定很醜。您也可以使用condition ? do_if_true : do_if_false表示法,這在這裏很方便。

<% if has_content_condition %> 
<div class="span3"> 
    <h5 class="pagination-centered"> 
    <%= link_to (image_tag "/img/folder.jpg", alt: "Buyer's Guides", width: "75px"), action: "index", filter: @filter, type: "buyers_guides" %> 
    <%= link_to "Buyer's Guides", action: "index", filter: @filter, type: "buyers_guides" %> 
    </h5> 
</div> 
<div class="span3"> 
    <h5 class="pagination-centered"> 
    <%= link_to (image_tag "/img/folder.jpg", alt: "Datasheets", width: "75px"), action: "index", filter: @filter, type: "datasheets" %> 
    <%= link_to "Datasheets", action: "index", filter: @filter, type: "datasheets" %> 
    </h5> 
</div> 
<% end %> 

我不確定這是否是您的想法。如果不明確,請發表評論,我很樂意提供幫助。 =)

+0

醜陋,但可以更快地閱讀過舊代碼時進行解析。 – sosborn

+0

控制器中的@filter怎麼樣? – DDDD

+0

你可以做<%if @filter%>'。你是這個意思嗎? (或者至少你曾經能夠在Rails 2中做到這一點,但是對我來說這已經有一段時間了。) –

0

如果我理解正確的話,你也可以這樣做:

if x.present? 
    x 
end 

因此,例如

@image = image.find(params[:id]) 
if @image.present? 
    <div class="span3"> 
    <h5 class="pagination-centered"> 
     <%= link_to (image_tag "/img/folder.jpg", alt: "Buyer's Guides", width: "75px"), action: "index", filter: @filter, type: "buyers_guides" %> 
     <%= link_to "Buyer's Guides", action: "index", filter: @filter, type: "buyers_guides" %> 
    </h5> 
    </div> 
end