neesop
neesop

Reputation: 49

Render a different view from any controller in Rails 4

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

Upvotes: 1

Views: 347

Answers (3)

Uday kumar das
Uday kumar das

Reputation: 1613

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

Upvotes: 0

Masudul
Masudul

Reputation: 21961

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

Upvotes: 1

Antarr Byrd
Antarr Byrd

Reputation: 26061

This is what partials are designed for.

Upvotes: 0

Related Questions