首页 > 解决方案 > 路线中可能存在不匹配约束的 Rails 问题

问题描述

我有一个问题,我不明白我该如何解决。

我有一个具有子类继承的模型......

class Content < ApplicationRecord
   TYPE = {
      article: {name: 'Reportage', class: 'Reportage'},
      news: {name: 'News', class: 'News'},
      guide: {name: 'Guida', class: 'Guide'},
      review: {name: 'Recensione', class: 'Review'},
      gallery: {name: 'Gallery', class: 'Gallery'},
      video: {name: 'Video', class: 'Video'}
    }
end

在 db 我有一个类型列来存储子类

class Review < Content

end

我的获取路线是

  get ':content_type/:content_slug(/:content_page_position_index/:content_page_slug)', to: 'contents#show', constraints: { content_type: /#{ContentsController::TYPES_FOR_ROUTING.values.map { |v| Regexp.escape v }.join('|')}/ }, as: :content

结果:"reportage|news|guida|recensione|gallery|video"

在控制器里面我有

TYPES_FOR_ROUTING = Content::TYPE.map{ |k,v| [v[:class],v[:name].downcase] }.to_h

结果:{"Reportage"=>"reportage", "News"=>"news", "Guide"=>"guida", "Review"=>"recensione", "Gallery"=>"gallery", "Video"=>"video"}

对于视频、画廊和新闻,我没有任何问题,因为意大利语名称与作为类名的英文名称相同。但是为了审查我有一个问题。

ActionView::Template::Error (No route matches {:action=>"show", :content_slug=>"porsche-panamera-hybrid-2021-la-prova-su-strada-in-provenza", :content_type=>"review", :controller=>"contents"}, possible unmatched constraints: [:content_type])

内容类型是“ review”,类名是review因为我想保留英文。但在路线中它寻找“ recensione”。我需要 SEO 有意大利语。

如何传递给路由以匹配成本约束,而不是类型属性 ( review),名称。我可以使用Content::TYPE,但我不知道如何通过它。

标签: ruby-on-rails

解决方案


推荐阅读