Rails 4表的SQL查询读取一列但不正确使用.where

时间:2016-03-19 08:21:36

标签: mysql ruby-on-rails

我需要根据使用&&构造的if条件生成结果。

在我看来,我需要做两件事:1)检查当前注册的玩家数量是否超过max_players指定的最大数量; 2)检查并确认用户尚未注册。

如果查询符合两个条件,我将返回错误。

<% if Participation.where(game_id: params[:id]).count >= Game.first.max_players && Participation.where(user_id: current_user.id).exists?(false) %>
 <p>Sorry, it failed.</p>

<% else %>

<div class="button-wrap">
            <br>
            <a class="btn rad-button2 wwt flat vertical" <%= link_to "Reserve Spot", reservation_path(id: params[:id]) %> </a>  
            </div>
        <% end %> 

尽管这两个条件的结构几乎完全相同,但第二个条件似乎是&#34; true&#34; (意思是,在这种情况下很奇怪,它是假的,并且current_user.id不存在),无论真实表中的内容是什么。

测试

  1. 我检查的第一件事是确定导致问题的条件。如果我删除第二个条件并转到一个游戏,其中表中具有相同game_id的匹配结果的#匹配参数,它将显示错误。到现在为止还挺好。但是,如果我仅在current_user已注册的游戏中使用第二个条件,则仍默认为else条件。

  2. 我确定有符合这两个条件的结果吗?我们假设我正在使用网址http://localhost:3000/lobby?id=2。好的,我想找到与{34}的id匹配的结果。&#34;

    Participation id: 4, user_id: 2, game_id: 2, ranking: 0, created_at: "2016-03-19 07:20:14", updated_at: "2016-03-19 07:20:14">, 
    Participation id: 30, user_id: 3, game_id: 2, ranking: 0, created_at: "2016-03-19 07:57:36", updated_at: "2016-03-19 07:57:36
    
  3. 如您所见,我们的匹配参数有两个game_id。在我的Game表格中,我指定最多为1个玩家进行测试,因此2&gt; 1,并且第一个条件通过(并且单独的测试成功产生错误)。

    第二个条件 - 当以user_id: 2身份登录时仍然无法产生错误,但它使用相同的where策略。

    知道我哪里错了吗?

    修改1 - 添加参与迁移

    class CreateParticipations < ActiveRecord::Migration
      def change
        create_table :participations do |t|
          t.references :user, index: true
          t.references :game, index: true
          t.integer :ranking, null: false, default: 0
    
          t.timestamps
         end
        end
       end
    

2 个答案:

答案 0 :(得分:1)

保持建议,将其移至方法:

<% if Participation.where(game_id: params[:id]).count >= Game.first.max_players && Participation.where(user_id: current_user.id).exists?(false) %>
参与

def self.below_max_and_unregistered?(game_id)
   Participation.where(game_id: game_id).count >= Game.find(game_id).max_players && 
     !(Participation.where(user_id: current_user.id).exists?)
end

然后如果你只是看电话

    <% if Participation.below_max_and_unregistered?(params[:id]) %>

为了调试你的情况失败的原因...尝试将它们分开并分别运行它们以查看哪个失败并解决了潜在的原因。

答案 1 :(得分:1)

exists?的{​​{3}}可以说明exists?的参数含义:

  

论证可以采取六种形式:

     
      
  • 整数 - 使用此主键查找记录。

  •   
  • String - 使用与此对应的主键查找记录   字符串(例如&#39; 5&#39;)。

  •   
  • Array - 查找与这些查找样式条件匹配的记录   (例如[&#39;名称喜欢?&#39;,&#34;%#{查询}%&#34;])。

  •   
  • 哈希 - 查找与这些查找样式条件匹配的记录(例如   如{name:&#39; David&#39;})。

  •   
  • false - 返回始终为false。

  •   
  • No args - 如果表为空则返回false,否则返回true。

  •   

(强调我的)。通过exists?(false)我不确定你认为你在做什么,但这种方法似乎表现得很好。