2014-10-02 28 views
0

在我的控制,我的定義位置的陣列,我用sample趕隨機字符串之一:如何將數組中的隨機字符串傳遞給視圖?

class IndexController < ApplicationController 
    def index 
    @location = ["England", "Scotland", "Wales", "Ireland"] 
    random_location = @location.sample 
    end 
end 

不過,我不知道在我的瀏覽器中顯示一個國家所需的代碼。

+1

只需使用'<(%)= @ location.sample%>'的視圖(index.html.erb)的內部。然後你就完成了。 – 2014-10-02 15:42:24

回答

1

使用Array#sample

class IndexController < ApplicationController 
    def index 
    # @location i_var will be available automatically inside the corresponding 
    # view of this action to the Index controller. 
    @location = ["England", "Scotland", "Wales", "Ireland"] 
    end 
end 

現在視圖內 - index.html.erb

Country is <%= @location.sample %> 
+0

完美,謝謝。 – samgbelton 2014-10-02 15:46:55

相關問題