ayounis90 ayounis90 - 7 months ago 35
Ruby Question

Rails undefined method 'model_name' for nil:nilClass with nested attributes

I have in my orders/edit.html.erb a form that begins like this:

<%= simple_form_for [@reservation, @order] do |f| %>


Orders Controller:

def edit
@reservation = Reservation.find_by_id(params[:reservation_id])
@order = Order.find_by_id(params[:id])
end


Association:

Reservation
:has_one
Order

Routes:

resources :reservations do
resources :orders
end


If my path resembles something like
/reservations/10/orders/10/edit
I end up getting an error from Rails saying
NoMethodError in Orders#edit
and
undefined method 'model_name' for nil:NilClass


When I create a new order the form works perfectly fine so not sure why i'm getting an error all of a sudden, can someone help me with this issue?

Answer

Current implementation is prone to failure when the URL supplied either a reservation ID or an order ID that is not valid. Two ways to handle this:

First, let Rails do it for you:

def edit
  @reservation = Reservation.find(params[:reservation_id])
  @order       = Order.find(params[:id])
end

This will raise an ActiveRecord::RecordNotFound error, which, in production, should lead users to your 404 page.

If you'd prefer to keep find_by_id and handle this manually, or to rescue from this error in a different way, you can do:

def edit
  @reservation = Reservation.find_by_id(params[:reservation_id])
  @order       = Order.find_by_id(params[:id])

  if @reservation.nil? || @order.nil?
    raise ActiveRecord::RecordNotFound.new # Or, do something else
  end
end

That would yield the same result as above ... just more code.

Comments