问题
I have a Rails model call InfoData and it has an attribute called error_codes. The codes are stored in an array like so [9,7,10,21] (integer[]) .
To recap
InfoData.first.error_codes
=> [9,7,5]
I try to use ransack on it in order to search if a specific code is present(via a select option). For error_codes_in (_in ransack predicate) I receive the following error
operator does not exist: integer[] = integer
LINE 1: ...ranch_id" WHERE "info_data"."error_codes" IN (9) A...
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
How should it be fixed?
回答1:
I think the easiest way would be to add a scope to your model and tell Ransack that it can use that scope. Something like this in your model:
class InfoData < ApplicationRecord
def self.error_codes_has(code)
# Or use `scope` to define this class method if you prefer
# doing it that way.
where(':code = any(info_datas.error_codes)', code: code)
end
def self.ransackable_scopes(auth = nil)
%i[error_codes_has]
end
end
And then use that scope in your search form:
<%= search_form_for @q do |f| %>
...
<%= f.label :error_codes_has %>
<%= f.search_field :error_codes_has %>
...
<% end %>
Alternatively, you could write your own ransacker that understands PostgreSQL arrays. That's probably more work and complexity than you need unless you're doing a lot of this.
来源:https://stackoverflow.com/questions/49340638/ransack-search-on-data-stored-in-array-operator-does-not-exist-integer-int