Dan Mitchell
Dan Mitchell

Reputation: 864

Rails routing dynamic pages to friendly url

I have an events website that needs to generate a new url for column name :domains that gets defined when a user creates the event in active admin i.e. http://www.re-work.co/:domains

I have event modal and events_controller and the view is events#show

In my routes file I have

match '/:domains' => "events#show"
  resources :events

My controller has this which looks like the problem but I dont know what to change it to:

class EventsController < ApplicationController
def show
  @event = Event.where(:domains => request.base_url).first

  if @event.nil?
    @event = Event.first
  end
end

A snippet of rake routes as all other routes are to do with admin

$ rake routes

         root            /                                         events#show
       events GET        /events(.:format)                         events#index
              POST       /events(.:format)                         events#create
    new_event GET        /events/new(.:format)                     events#new
   edit_event GET        /events/:id/edit(.:format)                events#edit
        event GET        /events/:id(.:format)                     events#show
              PUT        /events/:id(.:format)                     events#update
              DELETE     /events/:id(.:format)                     events#destroy

All these urls '/events/technology' or '/events/cities' or '/cities' or '/technology' go the same page, I am new to Rails and have read/watched rails routing tutorials but I can't figure it out. Can someone help?

Upvotes: 0

Views: 487

Answers (1)

fmendez
fmendez

Reputation: 7338

That is because this line:

match '/:domains' => "events#show"

Is matching everything after "/" and pointing it to the events#show action. That line is not necessary (you can remove it), since:

  resources :events

Will generate all the defaults routes for the events controllers.

Edit:

If what you're trying to do, is capture the whatever passed as /:domains to be used inside of the show action. Then that parameters is traveling as part of the params hash, for instance:

Parameters: {"domains"=>"technology"}

You can access it like this params[:domains]. In that case, you can leave the first line as it was:

match '/:domains' => "events#show"
match '/events/:domains' => "events#show" # add this one

resources :events   # <- delete this one, this right now is kind of redundant for what you're trying to do

and change the following code:

  @event = Event.where(:domains => params[:domains] ).first

Upvotes: 1

Related Questions