0

你好,我正在軌道上建立一個紅寶石每日星座運勢算命應用程序。我能夠讓頁面顯示隨機圖像,但是當用戶點擊按鈕來告訴他們的未來時,我想要一條消息與某個圖片相關聯。到目前爲止,我有有誰知道如何在rails中的ruby中的image_tags中使用條件語句。

<h1>What Does The Shadows Say About Your Heart</h1> 
<%= image_tag "#{rand(21)}.jpg", size: "300x300" %> 
<% if image_tag "0.jpg", size: "300x300" %> 
    <p>You have a thirst for vengeance.</p> 
<% end %> 
<% if image_tag "1.jpg" , size: "300x300"%> 
    <p>Soon you will face a great adversary.</p> 
<% end %> 
<% if image_tag "2.jpg" , size: "300x300"%> 
    <p>The road is not always clear.</p> 
<% end %> 

和我的控制器

class PagesController < ApplicationController 
def home 
end 

def show 
    @dark = ["0" , "1", "2", "3", "4", "5", "6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"] 
end 
end 

但是消息上的所有圖片顯示。請幫助它會很好。如果您需要查看更多代碼,請告訴我。注意:我沒有使用carrierwave活動管理員和回形針。

回答

1

我想這是你想要的

控制器

def show 
    @random = rand(21) 
end 

show.html

<h1>What Does The Shadows Say About Your Heart</h1> 
<%= image_tag "#{@random}.jpg", size: "300x300" %> 
<p><%= image_message(@random)%></p> 

page_helper.rb

def image_message(random) 
    message = {1=> 'You have a thirst for vengeance.', 2=> 'Soon you will face a great adversary.', 3=> 'The road is not always clear.'} 
    message[random] 
end 
+0

完美!這非常感謝你。如果可能,你能告訴我你是如何得到這個答案的。 – 2014-09-29 02:56:03

+0

我見過你的要求和助手正在滿足你的要求,所以我應用這種方法 – Arvind 2014-09-29 16:05:58

+0

Awww好的謝謝 – 2014-09-29 16:35:52

1

我不確定你想要達到的目標,但有一點是肯定的:將邏輯移出視圖;它可以讓你更靈活。

class ImageRandomizer 
    MAPPING = [ 
    [0, 'Financial good'], [1, 'Love life awesome'],... 
    ] 
    def image 
    random_image_mapping.first 
    end 

    def message 
    random_image_mapping.last 
    end 

    private 

    def random_image_mapping 
    @random_image_mapping ||= MAPPING[rand(1..21)] 
    end 
end 

controller.rb

def show 
    @random_image = ImageRandomizer.new 
end 

show.html.erb

<h1>What Does The Shadows Say About Your Heart</h1> 
<%= image_tag "#{@random_image.image}.jpg", size: "300x300" %> 
<p><%= @random_image.message %></p> 
+0

只是要清楚,你會包括類ImageRandomizer的顯示控制器。對不起,它很久沒有迴應。 – 2014-09-29 02:47:38