gem 在 github 地址:https://github.com/activerecord-hackery/ransack
Gemfile 中使用版本:
gem 'ransack', '1.6.6'
model 内容:
class Order < ActiveRecord::Base
scope :express_status, ->(status) do
case status
when 0
where('code = ?', '')
when 1
where('code <> ?', '')
else
nil
end
end
private
def self.ransackable_scopes(auth_object = nil)
%i(express_status)
end
end
controller 内容:
def index
@search = Order.ransack(params[:q])
@orders = @search.result.order('id desc').paginate(page: params[:page], per_page: 20)
end
view 内容:
<%= search_form_for @search, method: :get, class: 'form-inline' do |f| %>
<label>投递状态:</label>
<%= f.select :express_status,
{ '未投递' => 0, '已投递' => 1 },
class: 'form-control' -%>
</div>
<%= f.submit '搜索', class: 'btn btn-primary' %>
<% end %>
用来筛选订单是否已经投递的状态,库中存储的是 code 字符串;
现在的情况是我在 console 中执行Order.ransack({ :express_status => '0' })
可以得到如下结果:
Ransack::Search<class: Order, scope: {"express_status"=>"0"}, base: Grouping <combinator: and>>
但是执行Order.ransack({ :express_status => '0' }).result.to_sql
得到的 却怎么都:
SELECT `orders`.* FROM `orders`
求助 ransack 到底怎么利用 scope 搜索查询呢?