0

在 Rails 4 中,我有 3 个模型

class Tag < ActiveRecord::Base
  # attr_accessible :id, :name
end
class Category < ActiveRecord::Base
  # attr_accessible :id, :name
end

class Product < ActiveRecord::Base
  # attr_accessible :id, :name
  belongs_to :tag
  belongs_to :category
  delegate :tag_name, to: :tag
  delegate :category_name, to: :category
end

现在我有一个标签id: 1, name: "tag1"和一个类别id: 1, name: "category1",以及一个产品name: "product1", tag_id: 1, category_id: 1

我想将路由product与URLtagcategoryURL 匹配。前任:

/tag1/category1/product1
/category1/tag1/product1
/tag1/product1
/category1/product1
/product1

但不知道如何自动添加它。(我使用friendly_idgem 使 URL 变得更友好)这是我用来匹配路由的帖子,但它不是我想要的动态。当需求不仅tagcategory, 而且sub_category, super_category...routes.rbDRY

谁能给我另一个建议?

4

1 回答 1

0

这是您想要的丑陋解决方案:

#routes.rb
match "(:first_id)/(:second_id)/(:third_id)", to: "home#index", via: :get

正如您所提到的,您需要最后一个参数,这将是产品 ID。所以我们只需要得到最后一个。

#home controller
def index
  product_id = case 
  when params[:third_id].present?
    params[:third_id]
  when params[:second_id].present?
    params[:second_id]
  when params[:first_id].present?
    params[:first_id]
  end
 @product = Product.find(product_id)
end
于 2013-10-31T11:41:51.210 回答