【问题标题】:Changing a Rails Route to include another model attribute更改 Rails 路线以包含另一个模型属性
【发布时间】:2014-10-29 15:55:22
【问题描述】:

我在 Rails 4 中有一个电子商务网站,其中产品列表路线基于“资源列表”。这使得列表显示页面路由为 /listing/:id。我想在路线中包含产品名称并使其成为 /listing/:id/:name - 我该怎么做。

我看到了friendlyid gem,但如果有简单的方法,我更喜欢不使用gem。

这里是列表路线块:

  resources :listings do
        collection do
          post 'import'
          get 'search'
          get 'delete_all'
        end
   resources :orders, only: [:new, :create, :update, :show]
  end

根据 Jorge 在下面的回答,我添加了一个 get '/:name' => 'listings#show',但是当我搜索路线时,我收到一条错误消息“找不到没有 ID 的列表”,我仍然看到原始路线 /listings/:id 指向列表#show。

更新: 当我像上面那样粘贴新路由时,我点击产品时的默认路由仍然是/listings/:id。但是,当我输入新路由 /listings/:id/:name(例如 Listings/324/testlisting)时,我收到如下错误:

Started GET "/listings/324/brand" for 127.0.0.1 at 2014-10-29 12:55:35 -0700
Processing by ListingsController#show as HTML
  Parameters: {"listing_id"=>"324", "name"=>"brand"}
Completed 404 Not Found in 1ms

ActiveRecord::RecordNotFound (Couldn't find Listing without an ID):
  app/controllers/listings_controller.rb:189:in `set_listing'

'set_listing' 方法只是根据 id 查找列表。这是列表控制器的一部分。

  before_action :set_listing, only: [:show, :edit, :update, :destroy]

  def show
  end

  def set_listing
    @listing = Listing.find(params[:id])
  end

【问题讨论】:

  • 参数被命名为:listing_id,但您在Listing.find(params[:id]) 中搜索[:id]。这就是它失败的原因。

标签: ruby-on-rails


【解决方案1】:

这就是你要找的:

Rails3 Routes - Passing parameter to a member route

http://guides.rubyonrails.org/routing.html#nested-resources

resources :listing do
  get '/:name', to 'listings#whatever'
end

编辑:

你的路线看起来像这样吗?

  resources :listings do
    get '/:name', :to => 'listings#show'
    collection do
      post 'import'
      get 'search'
      get 'delete_all'
    end
    resources :orders, only: [:new, :create, :update, :show]
  end

编辑 2:

我建议创建一个新方法:

def show_by_name
   @listing = Listing.find_by(name: params[:name])
   render action: 'show'
end

并在路线上使用它:

get '/:name', :to => 'listings#show_by_name'

【讨论】:

  • 这给了我一个错误Couldn't find Listing without an ID
  • 粘贴传递给控制器​​的参数。
  • 我不确定如何找到正在传递的内容。我刚刚更新了我的帖子以包含我的代码块和其他一些细节。
  • 检查路由文件是否看起来像编辑后的答案。
  • 粘贴完整的错误堆栈跟踪以找出 id 有什么问题。 rake routes 应该只是返回路由,而不是试图找到任何东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多