Reputation: 6486
I'm using Rails 4 and have a Policy
model with a field policy_number
.
I'd like to create a (search-like) form where you input a policy_number
and it redirects you to that Policy's show page. I'm not sure how to go about this, should the form's action be policy_path
or something?
Thanks!
Upvotes: 0
Views: 46
Reputation: 999
The biggest problem here is that the user is inputting the policy number in the search form, so you don't have access to it at the time the form is rendered. Without using JavaScript, you won't be able to go directly to the policy by policy number entered.
Here's a possible starting point, though. Create a PolicySearchController
with an index
method, add a route for it, and create a simple form.
app/controllers/policy_search_controller.rb
class PolicySearchController < ApplicationController
def index
policy = Policy.where(policy_number: params[:policy_number]).first
if policy.present?
redirect_to policy
else
redirect_to :policies, alert: "No matching policy found."
end
end
end
config/routes.rb
resources :policy_search, only: :index
app/views/policies/index.html.erb
<%= form_tag policy_search_index_path, method: :get do -%>
<%= text_field_tag :policy_number -%>
<% end -%>
Now you can iterate on this to add JavaScript, fuzzy matching, etc. if desired.
Upvotes: 1