ruby # [duplicate]的未定义方法`articles_path'< ActionView::Base:0x0000000000b450>

b4qexyjb  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(122)

此问题在此处已有答案

Undefined method with "_path" while using rails form_for(4个答案)
11天前关闭。
这是名为Articles的控制器

def new
    @article =Article.new
  end
  

  def show
    @article=Article.find(params[:id])
  end

  def create
    @article=Article.new(article_params)
    if @article.save
      redirect_to @article
    else
      render :new, status: :unprocessable_entity
    end
  end

字符串
这就是风景

<h1>New Article</h1>

<%form_for(@article) do |form|%>
    <div>
        <%=form.label :title%><br>
        <%=form.text_field :title%>
    </div>
    <div>
        <%=form.label :body%><br>
        <%=form.text_field :body%>
    </div>
    <div>
        <%=form.submit%>
    </div>
<%end%>


这是路线图

get 'articles/new', to: 'articles#new'
  post 'articles/create', to: 'articles#create'


当我想访问路由http://localhost:3000/articles/new它给出错误未定义的方法`articles_path'为#ActionView::Base:0x0000000000b450

z2acfund

z2acfund1#

错误在form_for范围内引发。当给定新的article对象时,它必须猜测表单将被提交到的路径。按照约定,它尝试执行"#{object.model_name.plural}_path"
您的路由没有名称,也不会生成帮助器。您可以使用以下命令显式地给予它们命名:

get 'articles/new', to: 'articles#new', as: :new_article
post 'articles/create', to: 'articles#create', as: :articles

字符串
或者使用resources快捷方式:

resources :articles, only: %i[new create]

相关问题