简体   繁体   English

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

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

This is what i have done so far这是我到目前为止所做的

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 #搜索表单

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

I have created records and given appropriate association.s In the form, when i select a continent from the list to query the businesses, it does not query.我已经创建了记录并给出了适当的关联.s 表格,当我从列表中查询一个洲的 select 时,它不查询。 No errors are displayed不显示错误

This this what i get from the search params这就是我从搜索参数中得到的

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

This is the console log这是控制台日志

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

What am i doing wrong我究竟做错了什么

Since the Business model has_many:continents , you'll need to use plural continents , so:由于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