Jenny Blunt
Jenny Blunt

Reputation: 1596

Twice Nested Resource Form_For Issue

I have a double nested resource:

 resources :companies do 
    resources :orders do
      resources :comments
  end
 end

Am having issues when trying to include a form to create a comment in my orders show view. This is what I've tried:

<%= form_for([@order, @order.comments.build]) do |f| %>

However this gives me a no method error.

Any chance you can recommend the best way to deal with this.

Upvotes: 1

Views: 1041

Answers (1)

dombesz
dombesz

Reputation: 7909

You have to define the company as well. If you write rake routes you can see that you dont have order_comments_path because its double nested, so you will se something like company_order_commments_path which takes minimum two parameters, a company_id and an order_id. So if you really want to use this 3 level nester resource you have to add a @company variable to the form path. Like:

<%= form_for([@company, @order, @order.comments.build] do |f| %>

But in the most cases it's useless to define both company and order to identify an order, so the other option which could be better to add separately another route for the orders and comments, and this makes sense. In your routes.rb

...
resources :orders do
   resources :comments
end
...

So you can manipulate orders, without specifying the company. Also in the most general cases you don't get any important advantage by defining 3 level nested routes.

Upvotes: 3

Related Questions