Reputation: 57
I have a working search form built using Ransack with two separate search fields for two different Classes like so:
<%= search_form_for @q do |f| %>
<%= f.label :tags_id_in, 'Tags' %>
<%= f.select :tags_id_in, Tag.all.map{ |u| [u.name, u.id] }, { include_blank: "Tags" } %>
<%= f.label :sector_id_eq, 'Sector' %>
<%= f.select :sector_id_eq, Sector.all.map { |w| [w.name, w.id] }, {include_blank: 'Any'} %>
<%= f.submit "Search" %>
<% end %>
Each of these Classes are linked to a Company Class
class Company < ApplicationRecord
belongs_to :sector
has_many :company_tags
has_many :tags, through: :company_tags
accepts_nested_attributes_for :company_tags
end
I am trying to combine the two select fields into one. So far I can build the view for this like so:
<% combined = Sector.all + Tag.all %>
<%= f.select :combined, combined.map { |w| [w.name, w.id] }.sort, {include_blank: 'Any'} %>
Whilst the above works at displaying a single search form, there is no functionality to it. Can anyone help with this? Thanks in advance.
Upvotes: 2
Views: 2325
Reputation: 1257
Hooray, Ransack. It seems like this answer from 2013 is still valid: Search multiple models at once with Ransack
But if you're adventurous, maybe try this: https://github.com/activerecord-hackery/ransack/issues/131
You can add associations' columns/ransackers to the list of attributes by passing their names to #attribute_select via the :associations option.
Upvotes: 1
Reputation: 311
I'm not familiar with ransack, but maybe it's worth creating a new stand-in class? Just a PORO (plain ol' ruby object) go-between for the view and the model, using ransack for your queries rather than calling them directly from the form. You could build the tag list in that object as well.
You've got a lot of logic in your view, many frown on putting ActiveRecord queries there. A form object would fix that, and keep your controller simple as well.
Upvotes: 0