Rails 3 Routing: Using Two Dynamic Segments in a Path for the Same Model

What I'm trying to achieve is similar to the Github path for routes. For instance. I have a project called "question" in the URL / hjuskewycz / question. So my goal is to have routes where the first segment is the username and the second is the project name.

I tried several different approaches, this is the one I'm stuck with right now:

scope ":username" do resources :projects, :path => "" do resources :pictures end end 

Using

 project_path :username => project.owner.username, :id => project.to_param 

works as expected. However, it is tedious to always specify a username, although it is always the owner’s username. I would prefer

 project_path(:id => project.to_param) 

I know about default_url_options and url_for, and I dig in code. However, polyorphic_url does not use default_url_options.

I tried in routes.rb:

 resources :projects, :path => "", :defaults => {:username => Proc.new { "just_testing" }} 

since you can use proc for restrictions, but did not get it either.

I tried in project.rb

 def to_param "#{owner.username"/#{project.title}" end 

I spent too much time on this problem, and my current approach uses the convenience method to add the parameter: username. However, I think using this method everywhere to add a stink record (bad code smell). I wonder if there is a more elegant solution to this problem.

+4
source share
2 answers

I think you should not complicate the situation, just use something like this:

In Routes.rb

 match ':username/:projectname/' => 'projects#show_project' , :as => :show_project 

and in project_controller, just define it

 def show_project @user =User.find_by_username(params[:username]) @project =Project.find_by_slug(params[:projectname]) end 

Simpler is better, it saves time and is easy to understand for others.

0
source

You want to do something like this in your controller:

 before_filter :set_username def set_username Rails.application.routes.default_url_options[:username] = @user.name end 
0
source

Source: https://habr.com/ru/post/1368950/


All Articles