Easy routing for nested routes

I am trying to build simple_form_for in Rails 3.2 for @objects with a double-nested route, for example:

 /users/1/projects/2/objects 

The form:

 <%= simple_form_for @object, :url => user_project_objects_path(@user, @project), :html => { :class => 'form-horizontal' } do |f| %> 

In routes.rb:

 resources :users do resources :projects do resources :objects do collection { post :import } end end end 

My question is: what happens in the new and create actions of the Object controller?

So far - and I am getting a routing error - I have:

 def create @user = current_user @project = Project.find_by_user_id(@user) @object = @project.objects.build(params[:object]) if @object.save flash[:notice] = "Object was successfully created" redirect_to user_project_objects_path else render 'new' end end def new @user = current_user @project = Project.find_by_user_id(@user) @object = @project.objects.build end 

Any advice is greatly appreciated.

In response to Greg W:

 No route matches {:action=>"edit", :controller=>"objects", :user_id=>#<Object id: 8, source_lang_id: 1, source_content: "Kaffehaus", target_lang_id: 2, target_content: "cafe", domain_id: 2, owner_id: nil, created_at: "2013-01-04 06:36:55", updated_at: "2013-01-04 06:36:55", project_id: 2>} 

owner_id (User, i.e. current_user) is not updated - and this could be a problem (?)

+4
source share
2 answers

In the form you can use

 simple_form_for([@user, @project, object]) do 

You can use a relation to retrieve data, for example

 @project= current_user.projects 

instead

 @project = Project.find_by_user_id(@user) 
+4
source

I worked on this in the meantime. Perhaps this may be the usual guide for others working on double-nested routing, such as user -> projects -> objects (has_many, has_many)

In the controller of the object New action:

 @user = current_user @project = Project.find(params[:project_id]) @object = Object.new 

In the object controller, Create an action:

  @user = current_user @project = Project.find(params[:project_id]) @object = @project.objects.build(params[:object]) @object.owner_id = @user.id #owner id maps to User 

The routing error was the result of not specifying all the objects, user, project, and objects in

 user_project_objects_path(@project) 
0
source

All Articles