我正在尝试基于列 status production 上实现搜索/过滤器操作。status
列是整数类型。稍后,出于可读性的目的,我在status
列上使用了Enum DataType,如下所示。
class Production < ApplicationRecord
enum status:{
Preproduction:1,
Postproduction: 2,
Completed:3
}
end
然后,我开始使用搜索/过滤器功能来根据用户给出的状态获取记录。
productions_controller
def filter
if params[:filter]
@productions = Production.where('productions.status like ?', "%#{params[:filter]}%")
else
@productions = Production.all
end
end
查看
<%= form_tag [:filter, :productions], :method => 'get' do %>
<p>
<%= text_field_tag :filter, params[:filter] %>
<%= submit_tag "Filter", :status => nil %>
</p>
<% end %>
现在,只有在文本字段中输入诸如 1
2
或 3
之类的整数值时,我才能正确查询记录。当我像分配的Preproduction
一样输入状态时,我没有得到结果。我得到了一个空白页。我怎样才能解决这个问题 ?我该如何成功地接受字符串?
您可以做到这一点...
@productions = Production.where('productions.status like ?', "%#{Production.statuses[params[:filter]]}%")
枚举具有多元化的类方法,因此生产中的枚举status
具有哈希 Production.statuses
看起来像您的状态哈希,但符号更改为字符串。