Reputation: 97
I'm implementing a 'where' search in my Rails application, and it's able to search on all database columns except one of them. I've looked into this for quite a while, but can't figure out why it's happening.
I've currently built the search action entirely in my controller, as follows:
def search_results
keywords = "%"+params[:search_keywords]+"%"
@found_prospects = Prospect.where("current_role LIKE ?", keywords)
end
In my view, a user searches via a form:
<%= form_tag search_results_path, method: 'get' do %>
<%= text_field_tag :search_keywords %>
<%= submit_tag "Search" %>
<% end %>
And then a table is generated using the @found_prospects variable above, as below.
<% @found_prospects.each do |prospect| %>
<tr>
<td><%= prospect.id %></td>
<td><%= prospect.source %></td>
<td><%= prospect.first_name %></td>
<td><%= prospect.last_name %></td>
<td><%= prospect.country %></td>
<td><%= prospect.city %></td>
<td><%= prospect.current_role %></td>
<td><%= prospect.expertise_description %></td>
</tr>
<% end %>
My issue is: the current_role column in my db appears to return no results on this output, even when I can see it should be returning results.
I've tested other columns using the exact code above with 'current_role' replaced with other terms, and it works fine. On searching with current_role, no error is produced - there are simply no results returned.
Here are the database columns in my schema:
create_table "prospects", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "country"
t.string "city"
t.string "current_role"
t.string "expertise_description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "source"
t.string "expertise_tags", default: [], array: true
I've spent a while searching for anything unusual about the current_role column, but cannot see any issue on the face of things.
Any thoughts on potential solutions would be really welcome - in fact even ideas for additional things I can do to troubleshoot would be useful.
I'm using Rails 4.2.1, and Postgres for my db.
EDIT:
I have not found a solution to this problem, but a functional workaround has been to create an identical database column called current_position, and to replace references to current_role with current_position. So far this works, though of course it's not a real fix.
Upvotes: 2
Views: 447
Reputation: 97
Many of the commenters helped solve my problem, but I'm summarizing the answer below to help any who come across a similar issue.
There appeared to be a conflict with the current_role field (I believe caused by Pundit), which caused the column in my Prospect table to be ignored.
This was solved by stating the table explicitly in the code, e.g.
Prospect.where("prospects.current_role ILIKE ?", keywords)
To avoid future such conflicts, however, I have renamed the column current_position.
Upvotes: 1