Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new view to a controller in Rails

I have a controller, clients_controller, with corresponding index, show, edit, delete, new & form views. Is there a way to create a new view like clients/prospects.html.erb that acts the same way as clients/index.html.erb, except is routed at clients/prospects/?

I've tried this:

match '/clients/prospects' => 'clients#prospects'

And some other things in routes.rb, but of course get the error "Couldn't find Client with id=prospects".

The goal here is basically to have a prospects view and a clients view, and by simply switching the hidden field to a 1, it (in the user's mind) turns a prospect into a client (it's a CRM-like app).

like image 713
Trevan Hetzel Avatar asked Dec 04 '13 18:12

Trevan Hetzel


1 Answers

There's a couple of things you need to do. First you need to put the your custom route before any generic route. Otherwise Rails assumes the word "prospects" is an id for the show action. Example:

get '/clients/prospects' => 'clients#prospects' # or match for older Rails versions
resources :clients

Also you need to copy / paste the index method in your ClientsController and name it prospects. Example:

class ClientsController < ApplicationController
  def index
    @clients = Client.where(prospect: false)
  end

  def prospects
    @prospects = Client.where(prospect: true)
  end
end

Lastly, you need to copy the index.html.erb view and name the copy prospects.html.erb. In the example above you would have to work with the @prospects instance variable.

like image 163
migu Avatar answered Sep 30 '22 08:09

migu