我有两个模型:Business
和Category
. 在我business#index
看来,所有Business
名称及其关联的Category
. 我正在使用gem 并在我的模型has_scope
中添加了两个范围:和. 范围工作正常。当我从表单中选择一个类别并提交表单时,范围没有任何作用,但如果我将它硬编码到浏览器中的 URL 中,它就可以正常工作。Business
:by_category
search
search
by_category
collection_select
我注意到的是,如果我对 URL 进行硬编码,http://host/businesses?by_category=14
它就可以工作。这是我在日志中看到的:
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"}
但是,当我提交选择了类别的表单时,URL 显示为http://host/businesses?utf8=%E2%9C%93&search=&category%5Bid%5D=14
. 这是我以这种方式提交表单时在日志中看到的内容:
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"}}
我的表单传递参数的方式有问题,但我就是by_category
不能把手指放在上面。任何帮助将不胜感激。这是相关的代码。
楷模:
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
业务总监:
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
业务指标:
....
<%= 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 %>
...