gpt4 book ai didi

mysql - Ruby on Rails - 数组中的数据库查询

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

好吧,我正在尝试执行以下操作,我知道如何在 PHP 中执行此操作,但不知道如何在 Ruby on Rails 中执行此操作:

SELECT * FROM calls WHERE (status = 'open') OR (status = 'pending')

只需在数据库中的调用表中查找打开或待处理状态即可。

我想在 Rails 中执行此操作。目前我的 Controller 中有这个:

class CallsController < ApplicationController
def index
@calls = Call.all
end
end

这是我的观点:

<table>
<% @cals.each do |call| %>
<tr>
<th><%= link_to call.id, call_path(call) %></th>
<th><%= call.cname %></th>
<th><%= call.cbn %></th>
<th><%= call.email %></th>
<th><%= call.operator %></th>
<th><%= call.reason %></th>
<th><%= call.ticket %></th>
<th><%= call.created_at %></th>
<th><%= call.tier %></th>
<th><%= call.status %></th>
<th><%= link_to 'Edit', edit_call_path(call) %></th>
<th><%= link_to 'Remove', call_path(call), method: :delete, data: { confirm: 'Are you sure?' } %></th>
</tr>
<% end %>
</table>

最佳答案

试试这个:

def index
@calls = Call.where(status: ['open', 'pending'])
end

确保这些 where 调用不会泄漏到您的 Controller 中被认为是一种很好的做法,因为它们暴露了 Call 的许多内部结构。您可以在 Call 类中定义范围:

class Call < ActiveRecord::Base
scope :open_or_pending, -> { where(status: ['open', 'pending']) }
end

然后在 Controller 中使用它:

def index
@calls = Call.open_or_pending
end

请注意,现在 Controller 不需要知道 Call 有一个 status 字段及其值。

关于mysql - Ruby on Rails - 数组中的数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27674173/

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