【问题标题】:Rails route with dynamic slug followed by child ID带有动态 slug 后跟子 ID 的 Rails 路由
【发布时间】:2013-10-23 21:56:17
【问题描述】:

在我的模型中,卖家有很多商品。

卖家可以通过它的 slug 而不是它的 ID 访问:

config/routes.rb

get "/:slug", to: "sellers#show"

这很好用。

但是,我希望每个项目 URL 都根据 /:slug/:id 的格式包含其父 slug,例如/piano_man/5/joe_schmoe/344

以下作品:

config/routes.rb

get '/:slug/:id', to: 'items#show'

app/controllers/items_controller.rb

def show
  @item = Item.find(params[:id])
end

但它(显然)不会改变默认的 Item URL 行为,因为此代码只是忽略了 :slug 部分。

如何使默认 URL <%= link_to item %> 指向 /:slug/:id 而不是 /items/:id

请记住,“slug”来自父模型Seller,但 ID 来自项目本身。

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    我认为您需要命名自定义卖家商品路线,然后在使用 link_to 时引用该命名路线:

    config/routes.rb

    get '/:slug/:id', to: 'items#show', as: 'seller_item'
    

    app/views/items/index.html.haml

    = link_to item.name, seller_item_path(slug: item.slug, id: item.id)
    

    据我所知,这应该可以工作...可能还有一种方法可以覆盖您的 Item 模型上的 to_param 以返回 slug 和 id,而不必将它们直接指定为 seller_item_path 的参数。

    【讨论】:

    • 完美运行。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多