How to generate a unique ID and then make that the URL?
T开发者_StackOverflowhis is the etherPad workflow:
load http://ietherpad.com
click 'new pad' which takes you here: http://ietherpad.com/ep/pad/newpad
That then redirects to something like this:
http://ietherpad.com/1vcs1YUf1Z
How can I do this in rails?
- Have my rails controller new method generate a UID, and then redirect
- Have my rails routes somehow use that uID after the first / to find the right record and route to the right Pad Show method in the controller?
Thanks
The absolute easiest way is to do this:
In the model, have a callback
class Thing < AR::Base
# assuming you have a slug field
before_create :generate_slug
private
def generate_slug
self.slug = some_uid_algorithm
end
end
Then in the controller, use the edit action. Use the dynamic finder find_by_slug
and take in the id parameter. This returns the record if found, and returns nil if not found. If it's not found, call create
to get a new one, which invokes your slug callback.
def edit
@thing = Thing.find_by_slug(params[:id]) || Thing.create!
end
Direct your routes for this to the edit action of your controller. You may want a more robust way of determining what a valid slug is before you start creating records, but this is essentially how a "wiki" might work.
This might end up creating a bunch of junk records, so you'll want a way to sweep those. Some sort of state like "pending" or "unsaved" would take care of that - when the user updates the record, change the state from "unsaved" to "saved" and then sweep any "unsaved" docs that are 30 days old or something.
How does that sound?
精彩评论