ncarroll ncarroll - 7 months ago 32
Ruby Question

Rails routes parameters for both :id and :token

Is it possible to set up a routing parameter for both :id and :token?

There are ample resources out there on how to change the default route params:

resources :events, params: :token

def to_param
token
end


However I cant seem to find anything related to an "either or" scenario that would allow someone to access Events#show by either the event_id or the event_token. In my head, the following makes sense:

resources :events, params: :token || :id


Backstory:
I am setting up a "sharing link" so users without an account can view an events page, similar to google docs. To do this, a unique token is generated for each event, creating a websafe url (Protected sharing link in Ruby on Rails). The issue I am facing is trying to maintain routing using both the event_id and the event_token since the event page is also being viewed by account holders, where finding events by id is much easier.

Thank you.

Answer

Assuming that the url is the same shape -

# routes.rb
resources :events

# your urls
/events/15
/events/some-token-string

Rails will treat everything after the last slash as the id parameters. From there you can just query using an or clause

# Rails 5 with no raw SQL
Event.where(id: params[:id]).or(Event.where(token: params[:id])).first

# Rails 4 and lower (also works with Rails 5)
Event.where("id = ? or token = ?", params[:id], params[:id]).first
Comments