如何在 has_many 上实现搜索:通过关联

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 %>

我已经创建了记录并给出了适当的association.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 模型 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: ''} %>