I've got a two models: Business
and Category
. In my business#index
view, all Business
names are displayed in a table, along with their associated Category
. I'm using the has_scope
gem and added two scopes to my Business
model: :by_category
and search
. The search
scope works fine. The by_category
scope does nothing when I select a category from the collection_select
and submit the form, but if I hard-code it into the URL in my browser, it works fine.
What I've noticed is that if I hard code the URL as such http://host/businesses?by_category=14
it works. This is what I see in the logs:
Started GET "/businesses?by_category=14" for 127.0.0.1 at 2015-01-28 11:48:07 -0600
Processing by BusinessesController#index as HTML
Parameters: {"by_category"=>"14"}
But when I submit the form with a category selected, the URL appears as http://host/businesses?utf8=%E2%9C%93&search=&category%5Bid%5D=14
. This is what I see in the logs when the form is submitted this way:
Started GET "/businesses?utf8=%E2%9C%93&search=&category%5Bid%5D=14" for 127.0.0.1 at 2015-01-28 11:45:57 -0600
Processing by BusinessesController#index as HTML
Parameters: {"utf8"=>"✓", "search"=>"", "category"=>{"id"=>"14"}}
There's something wrong with the way my form is passing the by_category
param, but I just can't put my finger on it. Any help would be greatly appreciated. Here's the relevant code.
Models:
class Business < ActiveRecord::Base
belongs_to :category
...
...
scope :by_category, -> category { where(:category => category) }
scope :search, ->(search) { where(arel_table[:title].matches("%#{search}%")) }
end
class Category < ActiveRecord::Base
has_many :businesses
end
Business Controller:
class BusinessesController < ApplicationController
has_scope :by_category
has_scope :search
...
def index
@businesses = apply_scopes(Business).all.page(params[:page])
@categories = Category.all
end
end
Business Index:
....
<%= simple_form_for businesses_path, :method => 'get' do %>
<%= text_field_tag :search, '', placeholder: "Search..." %>
<%= collection_select :category, :id, @categories, :id, :name, :prompt => "Select Category" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
...