ruby-on-rails - ruby 洗牌!数组中的每个数组

标签 ruby-on-rails ruby arrays

我正在尝试做一个测验,所以我有很多问题和很多答案。我可以随机排列问题,因此它们不会每次都以相同的顺序出现。

q = Question.all().shuffle!

然后,我尝试打乱每个问题的所有答案:

q.each{ |i| i.answers.shuffle! }

但是,当我在 View 上遍历 q 时,我每次总是以相同的顺序获得每个问题的答案。关于我做错了什么的任何提示?

编辑

如果我这样做 @question = Question.find(1,2,3).shuffle! 我得到:

 [ #<Question id: 1, contenido: "lorem ipsum 1", created_at: "2014-02-09 13:13:56", updated_at: "2014-02-09 13:13:56">
#<Question id: 3, contenido: "lorem ipsum 3", created_at: "2014-02-09 13:13:56", updated_at: "2014-02-09 13:13:56">, 
#<Question id: 2, contenido: "lorem ipsum2", created_at: "2014-02-09 13:13:56", updated_at: "2014-02-09 13:13:56"> ]

如果我执行 @question.first().answers 我会得到一个这样的数组:

#<ActiveRecord::Associations::CollectionProxy [
#<Answer id: 1, contenido: "Black", correcta: true, created_at: "2014-02-09 13:13:56", updated_at: "2014-0213:13:56", question_id: 1>, 
#<Answer id: 2, contenido: "Blue", correcta: false, created_at: "2014-02-09 13:13:56", updated_at: "2014-02-09 13:13:56", question_id: 1>, 
#<Answer id: 3, contenido: "Yellow", correcta: false, created_at: "2014-02-09 13:13:56", updated_at: "2014-02-09 13:13:56", question_id: 1>]>

我的 Controller 方法如下所示:

def quiz
    @questions = Question.find(1,2).shuffle!
    @questions.each{ |i| i.answers.shuffle! }
end

在 View 中我这样做:

<% @questions.each_with_index do |pregunta, index| %>
    <div class="question-item <% if index == 0 %>current<% end %>">
    <p><%= index + 1  %>- <%= pregunta.contenido %></p>
    <%= hidden_field_tag "form[][pregunta]", pregunta.id  %>
    <%= hidden_field_tag "form[][respuesta]", "" %>
    <ul>
        <% pregunta.answers.each do |respuesta| %>
            <li><span class="radio" data-id="<%= respuesta.id %>"></span><span><%= respuesta.contenido %></span></li>   
        <% end %>
    </ul>   
    </div>
 <% end %>  

最佳答案

我可能会在访问它们时这样做,所以在 View 中...

<% @questions.shuffle!.each_with_index do |pregunta, index| %>
    <div class="question-item <% if index == 0 %>current<% end %>">
        <p><%= index + 1  %>- <%= pregunta.contenido %></p>
        <%= hidden_field_tag "form[][pregunta]", pregunta.id  %>
        <%= hidden_field_tag "form[][respuesta]", "" %>
        <ul>
            <% pregunta.answers.shuffle!.each do |respuesta| %>
                <li><span class="radio" data-id="<%= respuesta.id %>"></span><span><%= respuesta.contenido %></span></li>   
            <% end %>
        </ul>   
    </div>
 <% end %>

关于ruby-on-rails - ruby 洗牌!数组中的每个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664575/

相关文章:

Ruby:组合数组值

ruby - Time.stub( :now) {fake_time} do? 到底是什么

javascript - 如何将菊花链/点表示法中的 JavaScript 对象展开为具有嵌套对象和数组的对象?

javascript - 访问数组中的所有其他项 - JavaScript

html - 您如何链接到 ruby​​ on rails 中的网站图标?

ruby-on-rails - 我如何告诉 Rails 4 应用程序我的 SSL 证书在哪里?

ruby-on-rails - 从 rails 控制台命令创建用户?

ruby-on-rails - 使用 Rails 复制到冗余服务器?

arrays - 旧版本的 Perl 有不同的数组索引规则吗?

ruby-on-rails - 如何使用带有 PostgreSQL 的 Rails 通过自定义规则设置自定义序列号