开发者

Alternate between showing two images in a Rails view

开发者 https://www.devze.com 2023-03-09 02:36 出处:网络
Firstly I apologize for this as I am not a Rails programmer.. I just need to figure this out so that I can get back to productive work.

Firstly I apologize for this as I am not a Rails programmer.. I just need to figure this out so that I can get back to productive work.

I have inherited a RoR site and need to have an image that rotates randomly on page load. Simple, right?

My solution was to generate a random number between 0 and 2. If the number is above 1 show one image, else show the other. I had put this into a sidebar.erb file :

<div class="shadow">

<%- if rand(2) > 1 %>
        <img src="foo.png"/>
<%- else %>
        <img src="bar.png"/>
<%- end %>
                </div>

I 开发者_运维百科get the following error in the site logs:

warning: else without rescue is useless

I'm probably doing this completely wrong. Honestly, I just need this to work with minimal effort. Any help would be greatly appreciated.


First, you would need to calculate the random number in your controller and put it in an instance variable like :

@image_random = rand(2)

Then, in your view :

<% if @image_random == 1 %>
        <%= image_tag "foo.png" %>
<% else %>
        <%= image_tag "bar.png" %>
<% end %>

You can safely lose - after <% in Rails 3 :) It's been done automatically.

Bear in mind that rand(2) will either give back 0 or 1. So checking for random > 1 will always come out as false.

0

精彩评论

暂无评论...
验证码 换一张
取 消