簡體   English   中英

如何在 has_many 上使用 ransack 實現搜索:通過關聯

[英]How to implemet search with ransack on a has_many :through association

這是我到目前為止所做的

class Business < ApplicationRecord
    has_many :locations
    has_many :continent, through: :locations
    ...........

class Continent < ApplicationRecord
    has_many :locations
    has_many :businesses, through: :locations
    ..............

class Location < ApplicationRecord
  belongs_to :continent
  belongs_to :business
end

#搜索表單

<%= search_form_for @q do |f| %>
        <%= f.select :continent_id_eq, options_from_collection_for_select(Continent.all.order(:name), :id, :name, @q.continent_id_eq), { }, {class: ''} %>
        <%= f.search_field :name_cont %>

我已經創建了記錄並給出了適當的關聯.s 表格,當我從列表中查詢一個洲的 select 時,它不查詢。 不顯示錯誤

這就是我從搜索參數中得到的

localhost:3000/businesses?q[continent_id_eq]=1&q[name_cont]=&commit=Search

這是控制台日志

Business Load (1.6ms)  SELECT DISTINCT "businesses".* FROM "businesses" LEFT OUTER JOIN "locations" ON "locations"."business_id" = "businesses"."id" LEFT OUTER JOIN "continents" ON "continents"."id" = "locations"."continent_id" WHERE "continents"."id" = 3

我究竟做錯了什么

由於Business model has_many:continents ,您需要使用復數個continents ,所以:

<%= f.select :continents_id_eq, options_from_collection_for_select(Continent.all.order(:name), :id, :name, @q.continent_id_eq), { }, {class: ''} %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM