【问题标题】:How to implemet search with ransack on a has_many :through association如何在 has_many 上使用 ransack 实现搜索:通过关联
【发布时间】:2021-02-14 23:31:09
【问题描述】:

这是我到目前为止所做的

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

我已经创建了记录并给出了适当的关联。在表单中,当我从列表中选择一个大陆来查询商家时,它不会查询。没有错误显示

这是我从搜索参数中得到的

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

我做错了什么

【问题讨论】:

    标签: ruby-on-rails ransack


    【解决方案1】:

    由于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: ''} %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多