"Undefined_method, did you mean [pluralised] path?" form_with Rails 5.1.6 上的错误消息,正在使用资源

"Undefined_method, did you mean [pluralised] path?" error message on form_with Rails 5.1.6, using resources

我敢肯定,这是一个基本问题,但几天来我一直在用头撞这堵砖墙,很尴尬。所以,我有一个模型,名为 'Country'。

Routes.rb 看起来像:

Rails.application.routes.draw do    
  resources :country    
  resources :references
  get 'homepage/home'
end

country_controller.rb 看起来像:

class CountryController < ApplicationController

  before_action :set_country, only: [:show, :edit, :update, :destroy]

  def new
      @country = Country.new
  end

  def create
    @country = Country.new(:name => params[:name], :metatitle => params[:metatitle], :metadescription => params[:metadescription], :ogtitle => params[:ogtitle], :ogdescription => params[:ogdescription], :abouthtml => params[:abouthtml])

    if @country.save
        redirect_to country_index_path, notice: 'Country was successfully created.'
      else
        redirect_to :new, notice: 'Something went wrong :('
    end

  end

  def update
    if @country.update
        redirect_to country_index_path, notice: 'Country was successfully created.'
      else
        redirect_to :new, notice: 'Something went wrong :('
    end

  end


end

new.html 是:

<%= render 'form', country: @country %>

并且_form.html.erb是

    <div class="form">

<%= form_with(model: country, local: true) do |f| %>
  <div class="form_element">
    <%= f.label "Name" %>
    <%= f.text_field :name %>
  </div>

  <div class="form_element">
    <%= f.label "Meta Title" %>
    <%= f.text_field :metatitle %>
  </div>

  <div class="form_element">
    <%= f.label "Meta Description" %>
    <%= f.text_field :metadescription %>
  </div>

  <div class="form_element">
    <%= f.label "OG_Title" %>
    <%= f.text_field :ogtitle %>
  </div>

  <div class="form_element">
    <%= f.label "OG_Description" %>
    <%= f.text_field :ogdescription %>
  </div>

  <div class="form_element">
    <%= f.label "abouthtml" %>
    <%= f.text_field "About (HTML)" %>
  </div>
  <%= f.submit %>

<% end %>

</div>

在 /country/new 上,我收到一条错误消息,提示 'countries_path' 未定义,我的意思是 'country_path' 吗?我完全不知道哪里出了问题。

干杯! 麦克

routes.rb 你应该有:

Rails.application.routes.draw do    
 resources :countries    
end

加上你的任何其他内容,变化是:resources :countries 应该是复数

这是关于多元化。 routescontrollers 是复数形式,model 是单数形式。

# config/routes.rb
 Rails.application.routes.draw do    
  resources :countries # <= HERE    
  resources :references
  get 'homepage/home'
end

# apps/controllers/countries_controller.rb
class CountriesController < ApplicationController
# ...
end

另外,我知道这不是你问题的一部分,但也许你会想将创建操作更新为:

def create
  @country = Country.new(country_params)
  if @country.save
    redirect_to countries_path, notice: 'Country was successfully created.'
  else
    redirect_to :new, notice: 'Something went wrong :('
  end
end

protected

def country_params
  params.require(:country).permit(:name, :metatitle, :metadescription, :ogtitle, :ogdescription)
end