Ruby on Rails - 在 form_for Edit 中使用资源 :model 进行路由时未定义的方法"model_path"



有几个类似的问题存在,但我不能清楚地理解答案。我正在尝试为特定的模型制作一个具有CRUD操作的简单rails应用程序。我在使用form_for函数更新记录时特别遇到麻烦。

我的路线。rb文件:

Rails.application.routes.draw do
  root 'main#index'
  devise_for :users
  resource :models
  get 'main/index'
end
我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

最后是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 %>

当我实际运行这个并尝试编辑模型时,在我可以提交任何东西之前,我得到:

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

变化

redirect_to model_path

redirect_to @nc

如果你运行你的rake路由,你会看到model_path需要一个id -使用@nc告诉rails做你想做的事情。

最新更新