Going crazy on this one so thanks for any help!
I have a PetsController with an index, everything working fine. Now, I wanted to add a search form to the index, which instead of assigning @pets
to Pet.all
, will search the db with the user's query, like so:
def index
if ...
...
elsif params[:query]
@pets = Pet.where("name ~ ?", "#{params[:query]}")
else
...
end
end
and the form looks like this:
<%= form_with(url: '/pets', method: "get") do %>
<%= text_field_tag :query %>
<%= submit_tag 'Submit' %>
<% end %>
If I drop a binding inside the elsif, I see that I am indeed hitting it, and it's returning the proper results and assigning it to @pets
. But the page is still rendering all pets. Now, if I put the params in the URL, it works fine and only shows me what I want: http://127.0.0.1:3000/pets?query=Lime
So my question is, if it is correctly assigning the @pets
variable, why is it still rendering all Pets? And why does it work only with the params in the URL? I'm still pretty new at Rails so I appreciate your patience and help!
For further clarification:
The SQL that fires when I submit a query ('Fido') seems to work:
Rendering pets/index.html.erb within layouts/application
Pet Load (1.5ms) SELECT "pets".* FROM "pets" WHERE (name ~ 'Fido')
↳ app/views/pets/_pets.html.erb:23
Owner Load (0.3ms) SELECT "owners".* FROM "owners" WHERE "owners"."id" = $1 LIMIT $2 [["id", 8], ["LIMIT", 1]]
↳ app/models/pet.rb:11:in `name_with_owner'
Rendered pets/_pets.html.erb (Duration: 5.6ms | Allocations: 1472)
Rendered pets/index.html.erb within layouts/application (Duration: 6.2ms | Allocations: 1657)
However the page does not render and remains the same.
I'm fairly certain the problem lie in the form.