【发布时间】:2017-10-10 13:32:40
【问题描述】:
当尝试在 rails 中搜索记录时,我希望能够返回与该 ID 关联的所有记录。例如,如果我搜索“John”,我希望能够返回具有相同 fk 的所有记录。
表 1
| id |
------
| 1 |
| 2 |
表 2
| id | fk | name |
-------------------
| 1 | 1 | John |
| 2 | 1 | Doe |
| 3 | 2 | David |
| 4 | 2 | Smith |
SQL
控制器中的 Rails 代码
includes(:table2).where('table2.name LIKE ?', "%#{search}%").references(:table2)
SQL 返回
SELECT FROM `table1` LEFT OUTER JOIN `table2` ON `table2`.`fk` = `table1`.`id` WHERE (table2.name LIKE '%John%') AND `table1`.`id` IN (1)
这仅返回找到搜索的行。我将如何返回具有相同 fk 的记录?
table1 使用has_many :table2,table2 使用belongs_to :table1
提前致谢!
更新
index.html.erb 只包含一个表单,将输入提交给控制器,控制器运行查询并返回结果。
预期输入:约翰
预期结果:
| id | fk | name |
------------------
| 1 | 1 | John |
| 2 | 1 | Doe |
index.html.erb
<%= form_tag(categories_path, method: :get, :enforce_utf8 => false, id: "search-input") do %>
<%= text_field_tag :search, params[:search] %>
<button type="submit"></button>
<% end %>
categories_controller.rb
def index
@categories = Category.search(params[:search])
end
def Category.search(search)
includes(:category_type).where('category_type.name LIKE ?', "%#{search}%").references(:category_type)
end
【问题讨论】:
-
如果您只想要外键匹配的所有行,“搜索”逻辑是什么?只需使用
table1.table2s即可获取给定table1的所有table2记录。 -
@meagar 在前端我有一个搜索框,用户可以在其中搜索名称。搜索逻辑用于返回匹配记录与通过外键关联的记录
-
据我了解,他想在
name中搜索查询,然后返回具有该名称或共享相同fk的所有记录。所以对于John,结果将是Table1.find(1).table2s -
请提供您预期输入和输出的示例,并包含真实代码。您问题中唯一的 Ruby 代码示例不完整。
includes被束缚在什么地方? -
我仍然不清楚你在这里问什么。预期的输出是什么,
Category对象列表或CategoryType对象列表?where上的Category不能返回CategoryType对象的列表,假设您是table2实际上是为了代表CategoryTypes而table1是为了代表Category。
标签: mysql sql ruby-on-rails ruby