【问题标题】:Does anyone know how to use conditional statements inside image_tags in ruby on rails.有谁知道如何在 ruby​​ on rails 的 image_tags 中使用条件语句。
【发布时间】:2014-11-23 02:12:20
【问题描述】:

您好,我正在用 ruby​​ on rails 构建一个每日占星算命应用程序。我可以让页面显示随机图像,但是当用户单击按钮以告知他们的未来时,我希望一条消息与某张图片相关联。到目前为止我有

<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 active admin,也没有使用回形针。

【问题讨论】:

    标签: html ruby-on-rails ruby ruby-on-rails-4 conditional-statements


    【解决方案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
    

    【讨论】:

    • 完美!!!这太好了,谢谢。如果可能的话,你能告诉我你是如何得出这个答案的吗?
    • 我已经看到了您的要求,并且助手正在满足您的要求,所以我采用了这种方法
    【解决方案2】:

    我不确定你想要实现什么,但有一件事是肯定的:将逻辑移出视图;它还可以让您更加灵活。

    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>
    

    【讨论】:

    • 只是为了清楚你会在显示控制器中包含类 ImageRandomizer。很抱歉花了这么长时间才回复。
    猜你喜欢
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2011-04-11
    • 1970-01-01
    相关资源
    最近更新 更多