gpt4 book ai didi

ruby-on-rails - 在 rails 中搜索不同的模型查询

转载 作者:数据小太阳 更新时间:2023-10-29 08:51:28 26 4
gpt4 key购买 nike

好吧,我有多个模型,我想让客户在客户表和事件表上进行搜索这是我的模型

def self.search(search)
if search
Customer.find(:all, :conditions => ['first_name LIKE ?', "%#{search}%"])
Event.find(:all, :conditions => ['title LIKE ?', "%#{search}%"])
else
Customer.find(:all)
Event.find(:all)
end
end

哪个返回事件查询,但我想同时返回它们,如何组合查询?

更新:

这正是我想要做的,同时搜索多个模型,例如客户和事件。

我在我的模型搜索中定义了 def self.search(search) 并且我有一个 Controller

class SearchesController < ApplicationController
def query
#@results = Search.new(params[:search][:query]).results
@results = Search.search(params[:query])
end

我想在我的模型中查看客户和事件,但不确定该怎么做

这里是一个 View 示例,不确定它是否正确

<h1>Search Results</h1>
<% @results.each do |result| %>
<div>
<%= result.first_name %>
<% if admin? %>
<%= link_to 'Show', '#' %>
<%= link_to 'Edit', '#' %>
<%= link_to 'Destroy', '#' %>
<% end %>
</div>

<div>
<%= result.title %>
<% if admin? %>
<%= link_to 'Show', '#' %>
<%= link_to 'Edit', '#' %>
<%= link_to 'Destroy', '#' %>
<% end %>
</div>
<% end %>

最佳答案

在我看来,更好的方法是将每种类型的结果存储在实例变量中,而不是合并数据集。我这样说是因为我怀疑您的客户表和事件表是否相同。

class SearchesController < ApplicationController
def query
@customers = Customer.where('first_name LIKE ?', params[:query])
@events = Event.where('title LIKE ?', params[:query])
end

在您的 View 中,您可以显示在 Customers 中找到的结果和在 Events 中找到的结果。

关于ruby-on-rails - 在 rails 中搜索不同的模型查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11887025/

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