![](/img/trans.png)
[英]Delete record and all associated records, even if there are no associated records
[英]Include all records associated with a record that has been found when search is used in Ruby on Rails
尝试在 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 %>
category_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
我想你正在寻找的是
CategoryType.where(fk: CategoryType.where('category_types.name LIKE ?', "%#{search}%").select(:fk))
这将生成以下 sudo sql
SELECT
category_types.*
FROM
category_types
WHERE
category_types.fk IN (
SELECT
category_types.fk
FROM
category_types
WHERE
category_types.name LIKE '%JOHN%'
)
我通过执行一个查询来解决这个问题,该查询返回主表的所有记录,然后使用它们的 id 返回第二个表中的记录。 我认为这可能是同时获得所有结果的另一种方法,但现在这样做可以。
@records = joins(:category_typed).select('categories.id').where('category_types.name LIKE ?, "%#{search}%")
where(id: @records.ids)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.