[英]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.