【问题标题】:How to pass a Rails variable into a route如何将 Rails 变量传递给路由
【发布时间】:2016-05-11 02:13:30
【问题描述】:

在我的显示页面中,我想根据变量的值更改“查看更多”按钮的路径。例如,如果我在显示页面上查看位于佛罗里达州坦帕市的一座建筑物并单击“查看更多”,我想返回到 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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您在不需要的控制器中重复自己。看起来你想要一个参数化的路线:

    在你的 routes.rb 中:

    get "locations/:location", to: 'locations#show_location', as: :location_path
    

    然后,您可以在视图/控制器中将location 作为参数传递:

    location_path(location: @location.city)
    

    您可以在LocationsController 中进行简单的show_location 操作:

    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), I'我确信这并不理想,但它现在可以工作。
    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    • 2020-01-23
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多