0

I am working on rails app , In which I have created a table Product Name:string and Number: integer.

The application should give user a form where he can search a product by his number if product exists it should give product name from database.

My search.html.erb is this.

    <%= form_for @products, :url => { :action => "create" }, :html => {:class =>   "nifty_form"} do |f| %>
    <%= f.text_area :number, :size => "60x12" %>
    <%= f.submit "Search" %>
    <% end

What will be the definition of search Method in ProductController and routes i need to add in routes.rb?

1 Answer 1

1

Irrespective of nifty forms, this is how I would have done this:
In config/routes.rb replace resources :products' with

resources :products do 
  post 'search', :on => :collection
end

This will give me a search_products_path

In your view:

<%= form_for(:search, :url => search_products_path) do |f| %>
  <%= f.text_field :number, :placeholder => "Enter number to search" %>
  <%= f.submit "Search" %>
<% end %>

In your products_controller.rb

def search
  number = params[:search][:number]
  @result = Product.find_by_number(number)
  @not_found = true unless @result
end

In your views/products/search.html.erb, use @result to show the product information; take care while checking whether or not the desired product is actually found or not. I have set the boolean @not_found in case it doesn't exist.

Sign up to request clarification or add additional context in comments.

6 Comments

i am getting this error on search page .Couldn't find Product with id=search
After passing through controller action to search.html.erb ?
I am getting this error after updating all the files suggested by you then navigating to products/search.
I have change routes post path to get as through post path it was referring to show method but now i am getting error "undefined method `[]' for nil:NilClass"
@DeependerSingla, Please check that you do not have resources :products anywhere else in your routes.rb. If it is there, please remove that single line.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.