简体   繁体   中英

Correct template won't render Ruby on Rails 4

I'm using sunspot solr for searching on my Ruby on Rails app. I made a new search route, controller and pulling in what I would like to search for both the tool model and inventory model.

However, I can't find a way to render the search controller back to the root_path and/or root_url. I've tried a lot of different combinations and checked out this piece:

http://guides.rubyonrails.org/layouts_and_rendering.html

Right now the search controller is the following:

class SearchesController < ApplicationController

  def index
    @tools = Tool.search do
      keywords params[:query]
    end.results

    @inventories = Inventory.search do
      keywords params[:query]
    end.results

    format.html { render template: "home" }
  end

end

The render template: "home" is not working. If anyone knows how to redirect this to the root path that would be helpful.

Error message is :

ArgumentError in SearchesController#index too few arguments.

format local variable is nowhere defined in the index action which is resulting in the error ArgumentError in SearchesController#index too few arguments.

What you need to do is, enclose format.html within respond_to method call as:

respond_to do |format| ## format is defined here
  format.html { render template: "home" }
end 

Or as you are rendering the view in html format, you can directly use

render template: "home"  ## Removed format.html {}

Also, template option is used while rendering an Action's Template from Another Controller ie,

If you're running code in an SearchesController that resides in app/controllers directory, you can render the results of an action home to a template in app/views/welcome as:

render template: "welcome/home"

The point is you are either

using the template option in wrong context ie, if home action is present in SearchesController itself then you simply should do

render action: "home"

-OR-

you just forgot to add the view path in front of home ie if home action belongs to WelcomeController and home view resides under app/views/home then you should be specifying

render template: "welcome/home"

Tools/index worked!

class SearchesController < ApplicationController

  def index
    @tools = Tool.search do
      keywords params[:query]
    end.results

    @inventories = Inventory.search do
      keywords params[:query]
    end.results

    respond_to do |format|
      format.html { render template: "tools/index"  }
    end 
  end

end

您可以像这样使用redirect_to:

redirect_to '/your_route/to_home'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM