0

Another question from rails newbie. I am using friendly_id gem with mysql in rails 3.x

This is a design problem (may be easy in rails). I am expecting advises from rails experts. I am building a library listing app. Where user can view library by "metro-area" or by "city" in it. For example:

I wish to have URLs like:

www.list.com/library/san-francisco-bay-area

or

www.list.com/library/san-francisco-bay-area/palo-alto/

In database I have tables:

library
-------
id, name, city_id, slug

name is slugged here and city_id is FK

city
----
city_id, name, metro_area_id, slug

name is slugged here and metro_area_id is FK

metro_area 
----------
metro_area_id, name, state, slug

name is slugged here

So when a user points browser to www.list.com/library/san-francisco-bay-area/palo-alto

I wish to get list of libraries in san-francisco-bay-area/palo-alto. But my library table model is containing slug only for library's name. So how this URL can be parsed to find the city_id that can be used in library model and controller to get the list.

Please remember, I cannot rely only on the name of the city. I would have to find city_id of 'palo-alto' which is in metro 'san-francisco-bay-area'. Since slug for metro_area and city is in other tables, so what is the best way to design model and controller.

Show method of controller is:

def show
    @user = Library.find(params[:id])

    respond_to do |format|
       format.html # show.html.erb
       format.json { render json: @library }
    end
end

and model is

class Library < ActiveRecord::Base
  attr_accessible :name, :city_id, :slug
  extend FriendlyId
  friendly_id :name, use: :slugged
end

This will not work per my friendly URL requirement. So I would appreciate advice from experts :)

JVK
  • 3,782
  • 8
  • 43
  • 67

1 Answers1

0

Maybe you have found your solution, I'm new to rails as well, so I'm just guessing this would work out.

Since you wanna display slugs from two different models. I'm assuming the way to display ids would be something like

www.list.com/libraries/:id/cities/:id/metro_areas/:id

Which can be done through editing the route file by adding Nested Resources

As for just displaying two ids like

www.list.com/library/:city_id/:metro_area_id

Rails guide refers it as Dynamic Segments

After that, it's just a matter of converting the ids to slugs.

I also found this in FriendlyId's documentation which is addressing to your case.

Hope it helps

Firyn
  • 312
  • 3
  • 15