Fairglen
Fairglen

Reputation: 15

RoR ruby -- undefined method `model_name' for NilClass:Class

I'm having a trouble with the update on a class.

This is the view:

    <div id = "list">
        <%= form_for @list do |form| %>
        <%= render 'shared/error_messages', object: form.object %>
        <div class="list_fields">
         <%= form.text_field :name, placeholder:

and this is the controller:

     def update
         if @list.update_attributes(params[:list])
            flash[:success] = "List updated"
         else
            render 'edit'
         end
         redirect_to @list
    end

The routes are:

       resources :lists, only: [:create, :show, :destroy,:edit]

Now the problem is it keeps raising

      "undefined method `model_name' for NilClass:Class" 
           in line 2  --->   <%= form_for @list do |form| %>

And I can't seem to figure out why. Thanks in advance Leo

Upvotes: 0

Views: 52

Answers (1)

Lazarus Lazaridis
Lazarus Lazaridis

Reputation: 6029

You have to load the @list before you update its attributes.

def update
  @list = List.find_by_id(params[:id])
  if @list.update_attributes(params[:list])
    flash[:success] = "List updated"
  else
    render 'edit'
  end
  redirect_to @list
end

And by the way, the problem you see is not caused by your update action but by your edit action that redirects to this view.

You have to load the @list in both actions. In edit action in order to render the view, in update action in order to update the appropriate object.

Upvotes: 1

Related Questions