-
-
Save Spaceghost/1011204 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# It's pretty easy to set a custom method as the basis of your friendly_id if | |
# you want to incorporate information from another model in the friendly_id. | |
class City < ActiveRecord::Base | |
belongs_to :state | |
has_friendly_id :city_and_state, :use_slugs => true | |
# This will return something like "San Francisco, California". It can be used | |
# as a display name in your views, and also as the basis of the friendly_id | |
# because it will be processed by the plugin to remove spaces, punctuation, | |
# capital letters, etc. | |
def display_name | |
"#{state.name.titleize}, #{name.titleize}" | |
end | |
end | |
# The only major problem with this, is that if you state's friendly_id ever | |
# changes, the city's friendly_id will not be updated. Depending on your app, | |
# this may or may not be a problem. | |
# It's often better to simply rely on the tools that Rails provides: use a | |
# nested route, and just give both models a friendly_id: | |
# Models | |
class State < ActiveRecord::Base | |
has_friendly_id :name, :use_slugs => true | |
end | |
class City < ActiveRecord::Base | |
has_friendly_id :name, :use_slugs => true | |
end | |
# Route. Then `state_city_url(@state, @city)` will give you something like | |
# http://example.org/states/california/cities/san-francisco | |
map.resources :states, :has_many => :cities | |
# Somewhere in your cities controller: | |
@state = State.find(params[:state_id]) | |
@city = @state.cities.find(params[:id]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment