ncarroll ncarroll - 1 year ago 81
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

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

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.


Assuming that the url is the same shape -

# routes.rb
resources :events

# your urls

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