Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何将Rails变量传递到路由中_Ruby On Rails - Fatal编程技术网

Ruby on rails 如何将Rails变量传递到路由中

Ruby on rails 如何将Rails变量传递到路由中,ruby-on-rails,Ruby On Rails,在我的显示页面中,我想根据变量的值更改“查看更多”按钮的路径。例如,如果我在显示页面上查看佛罗里达州坦帕市的一栋建筑,然后单击“查看更多”,我想回到坦帕市的位置,再次查看坦帕市建筑的完整列表。但是,我希望链接中的路径根据特定建筑的城市进行更改: 类似这样的内容:位置{@location.city}\u路径 最好的方法是什么? 提前感谢您提供的任何帮助。 我的控制器: class LocationsController < ApplicationController def index

在我的显示页面中,我想根据变量的值更改“查看更多”按钮的路径。例如,如果我在显示页面上查看佛罗里达州坦帕市的一栋建筑,然后单击“查看更多”,我想回到坦帕市的位置,再次查看坦帕市建筑的完整列表。但是,我希望链接中的路径根据特定建筑的城市进行更改:

类似这样的内容:位置{@location.city}\u路径

最好的方法是什么?
提前感谢您提供的任何帮助。

我的控制器

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.rb中:

get "locations/:location", to: 'locations#show_location', as: :location_path
然后,您可以在视图/控制器中将
位置
作为参数传递:

location_path(location: @location.city)
您可以在
位置控制器中执行一个简单的
显示位置
操作:

def show_location
    @location = Location.find_by(city: params[:location])
    @photo = Photo.new

    if @location
       render @location.city
    end
end

感谢您的快速回复!我发布了routes.rb文件中的相关代码,我还在学习Rails,还没有使用过这样的配置。你能解释一下这是怎么回事吗?我有点不知所措。你是在建议我删除单独的城市操作吗?如果我对此了解得更多,我希望重构我的代码并实现这一点,我可以通过执行以下操作来使用现有的代码:location_path(@location.city.downcase),我确信这并不理想,但它目前正在运行。
def show_location
    @location = Location.find_by(city: params[:location])
    @photo = Photo.new

    if @location
       render @location.city
    end
end