Reputation: 297
In my show page I would like to change the route of a 'view more' button based on the value of a variable. For instance, if I'm looking at a building in Tampa Florida on the show page and I click 'view more', I want to go back to locations_tampa_path to see the full listing of buildings in Tampa again. However, I would like the path in the link to change based on the city of that particular building:
something like this: location_#{@location.city}_path
What is the best way to do this?
Thanks in advance for any help given.
My controller:
class LocationsController < ApplicationController
def index
@locations = Location.all
end
def new
@location = Location.new
end
def create
@location = Location.new(location_params)
if @location.save
flash[:notice] = "New location added"
redirect_to root_path
else
flash.now[:error] = 'Cannot send message'
render 'new'
end
end
def jacksonville
@locations = Location.where(:city => "Jacksonville")
end
def stpetersburg
@locations = Location.where(:city => "St. Petersburg")
end
def orlando
@locations = Location.where(:city => "Orlando")
end
def tampa
# @location = Location.find(params[:id])
@locations = Location.where(:city => "Tampa")
@photo = Photo.new
end
def show
@location = Location.find(params[:id])
@photo = Photo.new
end
private
def location_params
params.require(:location).permit(:name, :description, :address, :city, :featured)
end
end
Routes
get 'locations/tampa', to: 'locations#tampa'
get 'locations/jacksonville', to: 'locations#jacksonville'
get 'locations/orlando', to: 'locations#orlando'
get 'locations/st_petersburg', to: 'locations#stpetersburg'
resources :locations do
resources :photos, only: :create
end
Upvotes: 2
Views: 3268
Reputation: 11235
You're repeating yourself in your controller where you don't need to. It seems like you want a parameterized route:
In your routes.rb:
get "locations/:location", to: 'locations#show_location', as: :location_path
Then, you can pass location
as a parameter in your view/controller:
location_path(location: @location.city)
And you can have a simple show_location
action in your LocationsController
:
def show_location
@location = Location.find_by(city: params[:location])
@photo = Photo.new
if @location
render @location.city
end
end
Upvotes: 3