1

I have two models, book and course. In the books_controller I have a search method to find books by their ISBN.

def searchbook
  @searchedbook = Book.find_by_isbn(params[:q])
end

There is an input field in the index page that displays all the books. So my index.html.erb has this:

=form_tag({controller: "books", action: "searchbook"}, :method => :get) do
 .search_field
   %p
    Search Using ISBN:
   =text_field_tag :q
   =button_tag 'Go' , class: 'search-button' , type: :submit
%br

I have added this to my routes:

match 'searchbook', to: 'books#searchbook', via: :get

I just realized that my searchbook.html.erb is exactly the same as the show.html.erb. How can I get show.html.erb to render the results from searchbook

3 Answers 3

1

As you have same action for searchbook page view and form submit, so you need to check params q at URL searchbook action. So, whenever you submit the form, it will append parameter q and @searchedbook

def searchbook
  @searchedbook = Book.find_by_isbn(params[:q]) if params[:q].present?
end

At searchbook.html.erb

-if @searchedbook
  = render "show" # render the show partial
Sign up to request clarification or add additional context in comments.

2 Comments

I just got this error: 'Missing partial books/_show, application/_show with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder]}. Searched in: * "/Users/qqq/.rvm/gems/ruby-2.1.3/gems/web-console-2.0.0/lib/action_dispatch/templates" * "/Users/qqq/Documents/com381/bookiit/app/views" ' I wonder if it means that I should rename my show to _show
@neesop, you need a erb partial file at books directroy like _show.html.erb. If a have a file like show.html.erb than rename it to _show.html.erb.
0

This is what partials are designed for.

Comments

0

Use partials in searchbook.html.erb like render "show".

Comments

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.