0

There are a few similar questions that exist to this, but I could not clearly understand the answer. I am trying to make a simple rails application with CRUD operations for a specific model. I am specifically having trouble with doing this using the form_for function for updating the record.

My routes.rb file:

Rails.application.routes.draw do
  root 'main#index'
  devise_for :users

  resource :models
  get 'main/index'

end

My models_controller.rb

class ModelsController < ApplicationController

  def edit
    @nc = Model.find(params[:id])
  end

  def update
    @nc = Model.find(params[:id])
    @nc.update(model_params)
    if @nc.save
      flash[:success] = 'Changes saved.'
      redirect_to model_path
    else
      flash[:error] = @nc.errors.empty? ? 'Error' : @nc.errors.full_messages.to_sentence
      render :action => :edit
    end
  end

  def model_params
    params.require(:model).permit(:first_name, :last_name)
  end

end

and finally my model/edit.html.erb

<%= form_for @nc do |nc| %>
    <div class='container-fluid'>
      <form role='form'>
        <div class='row'>
          <div class='col-md-6'>
            <div class='form-group'>
              <%= nc.label :first_name %>
              <%= nc.text_field :first_name, :class => 'form-control', :value => @nc.first_name != nil ? @nc.first_name : '' %>
            </div>
            <div class='form-group'>
              <%= nc.label :last_name %>
              <%= nc.text_field :last_name, :class => 'form-control', :value => @nc.last_name != nil ? @nc.last_name : '' %>
            </div>
          </div>
        </div>
        <div class='row'>
          <div class='col-md-12'>
            <%= nc.submit 'Submit', class: 'btn btn-primary' %> <%= link_to 'Cancel', :back, class: 'btn btn-default' %>
          </div>
        </div>
      </form>
    </div>
<% end %>

When I actually run this and attempt to edit the model, before I can submit anything I get:

undefined method `model_path' for #<#<Class:0x00000003cb52c0>:0x007fb7022b18b0>
Did you mean?  models_path

1 Answers1

0

Change

redirect_to model_path

to

redirect_to @nc

If you run your rake routes, you'll see that model_path requires an id - using @nc tells rails to do what you want it to do.

MageeWorld
  • 402
  • 4
  • 14
  • I am running a development build on localhost. The error I get actually highlights "<%= form_for @nc do |nc| %>" as the issue. [This](http://stackoverflow.com/questions/14740702/form-for-undefined-method-user-path?rq=1) issue is perhaps the closest, but I do not think it should be necessary to manually set a url in this case. – itsfiziks Jul 04 '16 at 02:35
  • Your original post said the problem was undefined method 'model_path'. – MageeWorld Jul 04 '16 at 15:28