ruby on rails - How to modify (encode and decode) routes id, but without changes in the model or controller? -
i want expose database ids , encode/decode id routes helper. encoding use hashids gem.
now have:
routes.rb
get 'companies/:id/:year', to: 'company#show', as: 'companies'
company url:
/companies/1/2015
for id encoding have encode/decode helper methods:
def encode(id) # encode... return 'abc123' end def decode(hashid) # decode... return 1 end
how can implemented, id routes helper converted? must show url:
/companies/abc123/2015
and controller must automatically params id 1.
thanks answers! wont decode params id without changes in model or controller. after long consideration, have decided params id manipulate, before controller params. manipulate params in routes constraints.
example helper:
encoding_helper.rb
module encodinghelper def encode(id) # encode... return 'abc123' end def decode(hashid) # decode... return 1 end end
create path encode id:
companies_path(id: encode(1), year: 2015) # => /companies/abc123/2015
manipulate params in routes constraints:
lib/constraints/decode_company_id.rb
module constraints class decodeid extend encodinghelper def self.matches?(request) request.params['id'] = decode(request.params['id']).to_s if request.params['id'].present? true end end end
config/routes.rb
constraints(constraints::decodeid) 'companies/:id/:year', to: 'company#show', as: 'companies' end
after decode params id constraints und without manipulation in controller, params id 1.
Comments
Post a Comment