简体   繁体   中英

How can I disguise the ID part of my URL in rails when working without active record?

I have a URL that looks like this:

http://localhost:3000/activities/5NcsdzWvXbv

I'd like to make it look something like this:

http://localhost:3000/activities/river-rafting

I have a column in my non-activerecord database that stores the names of activities that I'd like to use instead of the id.

I've taken a look at friendly_ID gem but it looks like it won't work for me because of the way my model is set up.

class Leads
    include ActiveAttr::Model
end

Is there an easy solution to this?

I checked out an old rails question that recommended doing this:

def to_param
  self.name
end

This wouldn't work for me as my model file isn't connected to activerecord but instead an external nosql database.

Can I just make some modifications to my routing file or is there some other way to modify my URL?

Thanks for your time.

I don't quite understand your problem.

If your routes.rb is set up properly, then it will translate to activities/:id . So, if you're preparing data in controller, then it's up to you how you will fetch the data, passing params[:id] to your non-activerecord ORM.

The :id is just a placeholder. If you defined your route as activities/:slug , then you would access the id part using params[:slug]

Can you please post the part of the code which is not working for you?

Edit:

You still haven't posted any code which is not working for you. Anyways, I feel that you need to check some docs on working with multiple databases in Rails. Here is a sketch for starters:

Class YourClass 
 establish_connection "your_external_database"
end

Then you use that connection to perform queries to the db, using your slugs.

Edit2:

Ahhh... you need to obfuscate ids. It just boils down to exposing encoded ids and then decoding them at your (backend) side :)

Here is an example approach: How do I obfuscate the ids of my records in rails?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM