gpt4 book ai didi

mysql - Rails 4 表的 SQL 查询使用 .where 正确读取一列,但不能正确读取另一列

转载 作者:行者123 更新时间:2023-11-29 07:21:13 25 4
gpt4 key购买 nike

我需要根据使用 && 构造的 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 %>

尽管两个条件的结构几乎相同,但第二个条件似乎是“true”(奇怪的是,在这种情况下,它是 false,并且 current_user.id 不存在)无论真实表中的内容如何,​​始终如此。

测试

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

  2. 我确定有符合这两个条件的结果吗?假设我使用 URL http://localhost:3000/lobby?id=2。好的,我想查找 id 为“4”的匹配结果。

    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

如您所见,我们有两个 game_id 用于匹配参数。在我的 Game 表中,我指定最多有 1 名玩家进行测试,因此 2 > 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

最佳答案

docs对于 exists? 可以这样说明 exists? 的参数含义:

The argument can take six forms:

  • Integer - Finds the record with this primary key.

  • String - Finds the record with a primary key corresponding to this string (such as '5').

  • Array - Finds the record that matches these find-style conditions (such as ['name LIKE ?', "%#{query}%"]).

  • Hash - Finds the record that matches these find-style conditions (such as {name: 'David'}).

  • false - Returns always false.

  • No args - Returns false if the table is empty, true otherwise.

(强调我的)。我不确定您认为通过执行 exists?(false) 可以实现什么目的,但该方法的行为似乎与记录的一致。

关于mysql - Rails 4 表的 SQL 查询使用 .where 正确读取一列,但不能正确读取另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36099519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com