简体   繁体   中英

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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM