Seal
Seal

Reputation: 1060

Rails Nested routes undefined method

I keep getting an

undefined method 'orders_path' for #<#<Class:0x007faefee50a88>:0x007faefee414e8>

when navigating to my new order path url /users/1/orders/new

Been stuck on this, not sure what the deal is.

Routes:

devise_for :users, :path => 'accounts'

  resources :users, only: [:index, :show] do
      resources :orders
  end

root index:

<%= link_to "Create an Order", new_user_order_path(current_user.id) %>

form:

<%= form_for([@user, @order]) do |f| %>

<%= f.hidden_field :user_id %>

  <div class="form-group">
    <%= f.label :name %><br />
    <%= f.text_field :name, autofocus: true, class: "form-control" %>
  </div>

<% end %>

new:

<h1>New Order</h1>

<%= render 'form' %>

<%= link_to 'Back', user_orders_path(@user) %>

Upvotes: 2

Views: 507

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

When you write this:

<%= form_for(@order) do |f| %>

Rails is looking for orders_path, but you don't really have such a route as you have defined your orders resource nested under the users resource. So, you have to pass both: @user and @order to the form like this:

<%= form_for([@user, @order]) do |f| %>
    # your code goes here
<% end %>

If you write the form this way, then Rails will look for this path: user_orders_path which will match your defined route and will work and you won't get this error anymore:

undefined method 'orders_path' for #<#<Class:0x007faefee50a88>:0x007faefee414e8>

So, this will fix your current issue. But, there is another issue in your new.html.erb file where you currently have this:

<%= link_to 'Back', user_orders_path %>

You have to pass the @user as an argument to this method:

<%= link_to 'Back', user_orders_path(@user) %>

otherwise, it will fail again.

Hope this helps to solve your problems.

Upvotes: 2

Alexa Y
Alexa Y

Reputation: 1854

Since orders is nested on top of users, the form_for declaration will need to include both the user, and the order objects.

<%= form_for([@user, @order]) do |f| %>

Your new template will also need to have a reference to the given user.

<%= link_to 'Back', user_orders_path(@user) %>

Upvotes: 0

Related Questions