0

In Rails 4, I have 3 models

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

Now I have a tag id: 1, name: "tag1" and a category id: 1, name: "category1", and a Product with name: "product1", tag_id: 1, category_id: 1

I want to match route to product with both tag and category in URL. Ex:

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

but don't know how to add it automatically. ( I use friendly_id gem to make URL become more friendly) Here the post that I use to match the route, but it isn't dynamic as I want. When the requirement not only tag and category, but also sub_category, super_category... the routes.rb will increase very fast and doesn't DRY

Can anyone give me another suggestion?

Community
  • 1
  • 1
yeuem1vannam
  • 957
  • 1
  • 7
  • 15

1 Answers1

0

Here is the ugly solution of what you want:

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

as you mentioned, you need last params and that will be product id. So we just need to get last one.

#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
Ivan Shamatov
  • 1,406
  • 1
  • 10
  • 17