Mapping two models to use example.com/<name>
I have a user
model and a project
model in my app. I want both of these to have their show/edi开发者_开发知识库t
actions on http://example.com/<username or project name>
and http://example.com/<username or project name>/edit
If it were only one model, I could have added a match '/:username'
condition with a low priority in my routes. How would I go about doing this with multiple models?
This is probably a bad idea -- I would not recommend you do this. There is probably a better way to accomplish your needs -- what's wrong with example.com/users/123/
However, if you must do it, you could probably create a third controller, which, I'll call a shortcut controller.
First you'd need to route to the shortcut controller so the :/name
variable is passing to it for show and edit. See ideas for the routing in this Railscast.
Then in your shortcut controller actions you'd need to have a priority order (in case a user and project have the same name), where you first check for a username matching the given name and show/edit that or else look for a project and then show an error 404.
It would look something like:
def show
if @user = User.find_by_name(params[:name])
render 'users/show'
elsif @project = Project.find_by_name(params[:name])
render 'projects/show'
else
raise ActiveRecord::RecordNotFound, "Error message"
end
end
Anyway, that could probably be made to work, but again I'm not sure it's a good idea, and I suspect there are a lot of kinks in that idea you'll have to work out. Good luck!
精彩评论