rails 5 enum where “like”

旧街凉风 提交于 2019-12-12 22:43:36

问题


I'm trying to query an activerecord model enum and use the like operator in the where method, and it just doesnt work. Is there some trick to allow me to query an enum this way? Works fine on regular columns. Here it is in the console.

Regular string column (title) works as shown below

irb(main):092:0> Proposal.select(:id,:department,:status).where('title like "test%"')
Proposal Load (0.3ms)  SELECT  "proposals"."id", "proposals"."department", "proposals"."status" FROM "proposals" WHERE (title like "test%") LIMIT ?  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Proposal id: 7, department: 1, status: "In Progress">, #<Proposal id: 61, department: 2, status: "Won">]>

However, trying it on an enum, gives no results.

irb(main):094:0> Proposal.select(:department,:status).where('status like "Wo%"')
Proposal Load (0.3ms)  SELECT  "proposals"."department", "proposals"."status" FROM "proposals" WHERE (status like "Wo%") LIMIT ?  [["LIMIT", 11]]
=> #<ActiveRecord::Relation []>

Any idea why I can't use like operator on enum? I'm trying to use this to filter a view with datatables.net server side processing.


回答1:


Enum stores data as integer like 0,1,2,3... Then rails map number to enum value defined in model. That is the reason why you doesn't get result



来源:https://stackoverflow.com/questions/46079147/rails-5-enum-where-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!