在我的展示页面中,我想根据变量的值更改“查看更多”按钮的路径。例如,如果我在展会页面上看佛罗里达州坦帕市的一幢建筑物并点击“查看更多”,我想回到locations_tampa_path再次查看坦帕的建筑物的完整列表。但是,我希望链接中的路径根据特定建筑的城市进行更改:
类似这样的内容:location_#{@location.city}_path
这样做的最佳方式是什么?
提前感谢您给予的任何帮助。
我的控制器:
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
路线
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
答案 0 :(得分:3)
您在自己不需要的控制器中重复自己。您似乎想要一个参数化路线:
在您的routes.rb中:
get "locations/:location", to: 'locations#show_location', as: :location_path
然后,您可以在视图/控制器中传递location
作为参数:
location_path(location: @location.city)
您可以在show_location
中执行简单的LocationsController
操作:
def show_location
@location = Location.find_by(city: params[:location])
@photo = Photo.new
if @location
render @location.city
end
end